I want to replace the current index number of items of list with a new customised serial number
I have a list with different variables and they are indexed using below code
list_a = ["alpha","beta","romeo","nano","charlie"]
for idx, val in enumerate(list_a, start=1):
print("index number for %s is %d" % (val, idx))
This gives me following results.
index number for alpha is 1
index number for beta is 2
index number for romeo is 3
index number for nano is 4
index number for charlie is 5
Now I want to replace the above index numbers from 1 to 5 with a customized list as below
index number for alpha is 1Red
index number for beta is 2Blue
index number for romeo is 3Purple
index number for nano is 4Red
index number for charlie is 5Blue
Appreciate the help and many thanks in advance.
if I understand you want replace the values of your list_a
in a specific sequence and there is no logical/rule, Right?
So you can do it in lots of ways, but if do it you'll lose your date from the list_a, so I'll show you another two ways to solve this problem, ok?!
First way by for:
list_a = ["alpha","beta","romeo","nano","charlie"]
cust_list = ['Red', 'Blue', 'Purple', 'Red', 'Blue'] #create a new list
#Create your logical by for
for id_a, id_b, i in zip(list_a, cust_list, range(5)):
cust_list[i] = str(i+1)+id_b
#Make some changes in your code and run it
for idx, val in enumerate(list_a, start=1):
print("index number for %s is %s" % (val, cust_list[idx-1]))
Second way by list comprehension and for:
list_a = ["alpha","beta","romeo","nano","charlie"]
cust_list = ['Red', 'Blue', 'Purple', 'Red', 'Blue'] #create a new list
#adding new items by list comprehension
[cust_list.insert(i,str(i+1)+cust_list[i]) for i in range(len(list_a))]
#deleting old items
for i in range(5):
del cust_list[-1]
#Make some changes in your code and run it
for idx, val in enumerate(list_a, start=1):
print("index number for %s is %s" % (val, cust_list[idx-1]))
Your new data are storaged in cust_list
you can check it out by print(cust_list)
.