Home > Blockchain >  Can we use f-strings to create lists in for loop and then use it to append the data in the same iter
Can we use f-strings to create lists in for loop and then use it to append the data in the same iter

Time:09-07

Requirement:

  • I want to run a for loop which would create a new list as per it's range
  • Once the list is created, I want the list to append the data running in the iteration
  • If I've range of 5 then 4 lists should be created and should be used to append the data inside it.

Attaching a code which is totally wrong, But it explains what I want

for b in range(1,5):
f"abc{b}" = []
d = f"***{b}"

f"abc{b}".append(d)



print(abc1)
Output - ***1
print(abc2)
Output - ***2

Is something like this possible? Or any alternative solution?

For all the users who've answered my previous question, I request you to please update your comments and answers.

CodePudding user response:

Use a Dictionary.

Example:

mydict = {};
for i in range (1,5):
        mydict[i] = [i]

This will create an object like this:

{1: [1], 2: [2], 3: [3], 4: [4]}

Which you can iterate through/interact with as needed.

CodePudding user response:

If I understand your intentions right, you don't need 100 variables, you just have to create a list of lists and append the elements this way

list_of_lists = []

for i in range(1,5):
    list_of_lists.append([i])

print(list_of_lists)

CodePudding user response:

You can do with list comprehension,

In [80]: result = [[i] for i in range(1, 5)]

In [81]: result
Out[81]: [[1], [2], [3], [4]]

or,

In [82]: result = []
In [83]: for i in range(1, 5):
    ...:     result.append([i])

Edit

I understand from your comments that you want to create a new variable on each iteration. I think that's a bad approach, you could use a dictionary instead.

THIS IS A BAD APPROCH

In [84]: for i in range(0, 5):
     ...:     globals()[f"list_{i}"] = [i]

In [85]: print(list_0, list_1, list_2, list_3, list_4)
[0] [1] [2] [3] [4]

You can use a dictionary instead like this,

In [86]: {f'list_{i}': [i] for i in range(0, 5)}
Out[86]: {'list_0': [0], 'list_1': [1], 'list_2': [2], 'list_3': [3], 'list_4': [4]}

CodePudding user response:

You may want to use dict comprehension

#num of lists you want
num_of_lists = 5
mylists = { f'list_{i}':[i] for i in range(1,num_of_lists )}

# set the dictionary of named-lists to your local variables
# WARNING: this will overwrite any local variables with the same name

locals().update(mylists)
print(list_1)
# [1]
  • Related