Home > front end >  Python: how to dynamically add a number to the end of the name of a list
Python: how to dynamically add a number to the end of the name of a list

Time:11-04

In python I am appending elements to a list. The element name I am getting from an input file, so the element_name is an unknown. I would like to create a new list by adding a number to the end of the original list (dyn_list1) or even by using one of the elements in the list (element_name). How can this be achieved?

dyn_list = []
for i in range(4):
    dyn_list.append(element_name)

I thought it would look something like:

dyn_list = []
for i in range(4):
     dyn_list%i.append(element_name)
 print(dyn_list)

But that obviously doesn't work.

CodePudding user response:

I'm not sure I understand correctly, but I think you want to add the data you get by reading a txt file or something like that at the end of your list. I'm answering this assuming. I hope it helps.

list_ = ["ethereum", "is", "future"]  #your list
new_list = []                         #declare your new list
list_len = len(list_)                 #get list len
with open('dynamic.txt') as f:        #read your file for dynamic string

    lines = f.readlines()


while list_len:   # so that the dynamic data does not exceed the length of the list

    for i in range(list_len):
        new_element = list_[i]   "."   str(lines[i])
        new_list.append(new_element)
        list_len -= 1  #Decrease to finish the while loop

for p in new_list: print(p)

CodePudding user response:

You may want to use a dictionary instead of a list. You could use something like

dyn_list = {}
for i in range(4) : 
    element_name = ...#some code to get element_name
    dyn_list[i] = element_name

Then if you want to retrieve the ith element, you can use

dyn_list[i]

  • Related