0

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.

Bhavya Lodaya
  • 140
  • 1
  • 10
  • Based on the question and shown sample output, multiple solutions are given below. Are you sure your desired output is correctly shown above? – pyeR_biz Sep 06 '22 at 11:34
  • You mean you don't want to declare the name/variables of the lists you create manually? because below solutions show how to create a list_of_lists in one line -- without if else statements. – pyeR_biz Sep 06 '22 at 12:29
  • Im still not sure what you are looking for, but try my updated answer. – pyeR_biz Sep 06 '22 at 12:42

4 Answers4

0

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]}
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

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]
pyeR_biz
  • 986
  • 12
  • 36
0

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)
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
Quartyom
  • 11
  • 1
0

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.

Jimerson
  • 96
  • 1
  • 5