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.
Solution I know:
- I can create 4 list manually and can assign them with if else condition, But this won't help if I want to create 100 list
My code:
a = []
b = []
c = []
d = []
for i in range (1,5):
if i == 1:
a.append(i)
elif i == 2:
b.append(i)
elif i == 3:
c.append(i)
else:
d.append(i)
print(a,b,c,d)
Output
[1] [2] [3] [4]
Here we are creating and appending 4 list manually,
Attaching a code which is totally wrong, But explains what I want
for b in range(1,4):
f"abc{b}" = []
f"abc{b}".append(b)
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]