Home > database >  Can anyone help me understand how this for loop is running?
Can anyone help me understand how this for loop is running?

Time:03-20

I am pretty familiar with the enumerate and 'range(len(iterable)' way of looping through a for loop. However, for whatever reason I can't seem to understand why the for loop is producing the following output.

lst = [-2, 0, 4, 5, 1, 2]

for num, b in enumerate(lst):
    print(lst[b])

Output :

1
-2
1
2
0
4
  • I understand if I were to print(lst[num]) it would print the items of the list.
  • If I were to print(i) I would also print the items of the list.
  • If I print(num) I would print the indices.

I just can't figure out where the output is getting the numbers from.

CodePudding user response:

For the enumerate function, b refers to the elements. But since the elements are also valid indices for the loop, they return a value. SO:

lst = [-2, 0, 4, 5, 1, 2]

for num, b in enumerate(lst):
    print(lst[b])

In this Every iteration is:

1) b = -2 => print(lst[b]) => lst[-2] => 1
2) b = 0 => print(lst[b]) => lst[0] => -2
3) b = 4 => print(lst[b]) => lst[4] => 1
4) b = 5 => print(lst[b]) => lst[5] => 2
5) b = 1 => print(lst[b]) => lst[1] => 0
6) b = 2 => print(lst[b]) => lst[2] => 4

Hence this is valid

CodePudding user response:

lst = [-2, 0, 4, 5, 1, 2]

for index, value in enumerate(lst):
    print(value)
    # Prints each value
  
for index, value in enumerate(lst):
    print(index)
    # Prints each index

for index, value in enumerate(lst):
    print(lst[index])
    # Prints each value (but not really benefiting from enumerate)

for index, value in enumerate(lst):
    print(lst[value])
    # Meaningless 
    # Only works since value itself is an int 
    # Prints some element in lst whose index equals to value

CodePudding user response:

If you're confused about why a piece of code is doing what it doing, it's frequently helpful to have it print out exactly what it's doing. In this case, printing out the values of b:

>>> lst = [-2, 0, 4, 5, 1, 2]
>>> for b in lst:
...     print(f"lst[{b}] = {lst[b]}")
...
lst[-2] = 1
lst[0] = -2
lst[4] = 1
lst[5] = 2
lst[1] = 0
lst[2] = 4

As you can see, the b values go through the lst elements in order, and the lst[b] values that get printed on the right (which are the only values you printed originally) do indeed correspond to what you get by indexing lst.

Note that lists are zero-indexed, so lst[0] is the first element (-2), and a negative index counts that many spaces from the end, so lst[-2] is the second element from the end (1, the same as lst[4]).

  • Related