Reputation: 131
The code below seems to be iterating through a 2d list using another list which conceptually doesn't make much sense to me. What would be the in range equivalent to the code below, using lens as I'm finding it quite difficult to understand.
I've changed the variable names as I'm working on coursework but if its too abstract I can add in the original variable names.
#list2 is a 2d list
#list1 is a normal list
for list1 in list2
for k in range(n) #n and k are constants
#any if statement
Upvotes: 0
Views: 57
Reputation: 13120
A "2D" list is just a list where each element is itself a list. To access each element of the lists inside the "main" list, do
for list1 in list2:
for element in list1:
print(element)
If you want a version using range
:
L2 = len(list2)
for i in range(L2):
list1 = list2[i]
L1 = len(list1)
for j in range(L1):
element = list1[j]
print(element)
As should be clear from the above, using range
in a for loop is very rarely a good idea, as the code is much less readable.
Upvotes: 1