0

I have 2 list in python, list1 and list2, i need to access this list in loop one by one, how can do we do it dynamically?

16th Oct 2018, 1:36 PM
Bishu Giri
Bishu Giri - avatar
6 Réponses
+ 3
This sounds like something you'd usually use an array (or a list) for. for i in range(5): mylist[i] = [1, 2, 3] If you can't or don't want to use a list of lists, you can use eval() or exec(), depending on what you want to do: for i in range(5): exec('mylist' + str(i) + ' = [1,2,3]') for i in range(5): print(eval('mylist' + str(i))) # output: [1,2,3] [1,2,3] ...
16th Oct 2018, 2:47 PM
Anna
Anna - avatar
+ 2
Lets say that you have a 2-dimentional array, you typically use nested loops. EX : a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') #OUTPUT : 1 2 3 4 5 6 7 8 9 so The first loop iterates through the row number, the second loop runs through the elements inside of a row.
16th Oct 2018, 1:48 PM
khalid el badaoui
+ 1
to run through the list use a for loop: for element in list1: # do something for element in list2: # do something
16th Oct 2018, 1:40 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 1
One way would be to have a dictionary of all your lists, like: d={0: list0, 1: list1...) Then you can access the lists in your loop via d[i], d[i][3], d[i].append and so on.
16th Oct 2018, 2:52 PM
HonFu
HonFu - avatar
0
What exactly do you want to do?
16th Oct 2018, 1:58 PM
HonFu
HonFu - avatar
0
Each list name is a concatenation of "list" + number, each time I want to access a single list whose name will be "list" + STR(i)
16th Oct 2018, 2:30 PM
Bishu Giri
Bishu Giri - avatar