Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need the 'index' variable to move down a row in a list of list? Doesn't the 'for loop' do that automatically?

Tags:

python

can someone please help me bridge my gap in understanding?

Why is the 'index' variable necessary to 'move down' a row in a list of lists? I thought a for loop did that automatically.

#I am working with the following data

url = "https://en.wikipedia.org/wiki/List_of_helicopter_prison_escapes"

data = data_from_url(url)

for row in data[:3]: #I use this because I have to get rid of the information in the column named 'Details'
    print(row)
#"The assignment says: Initialize an index variable with the value of 0. The purpose of this variable is to help us track which row we're modifying." - (I don't get this explanation)

index = 0
for row in data:
    data[index] = row[:-1]
    index += 1

#Why is the following code not enough if a 'for loop' iterates through each row in a list of lists?

for row in data:
    data= row[:-1]
like image 778
Nadya Jawahir Avatar asked Dec 17 '21 11:12

Nadya Jawahir


People also ask

How do you increment an index in python?

In python, if you want to increment a variable we can use “+=” or we can simply reassign it “x=x+1” to increment a variable value by 1. After writing the above code (python increment operators), Ones you will print “x” then the output will appear as a “ 21 ”. Here, the value of “x” is incremented by “1”.

How do you start a second element loop in python?

If you want to iterate through a list from a second item, just use range(1, nI) (if nI is the length of the list or so). i. e. Please, remember: python uses zero indexing, i.e. first element has an index 0, the second - 1 etc. By default, range starts from 0 and stops at the value of the passed parameter minus one.


1 Answers

Let's try both and see what happens:

>>> data = [[1,2,3],[4,5,6],[7,8,9]]
>>> index = 0
>>> for row in data:
...     data[index] = row[:-1]
...     index += 1
...
>>> data
[[1, 2], [4, 5], [7, 8]]

Looks good; all the rows without their last elements.

>>> data = [[1,2,3],[4,5,6],[7,8,9]]
>>> for row in data:
...     data = row[:-1]
...
>>> data
[7, 8]

Oops, that's just the last row without its last element, since that's what you assigned to data.

There are less convoluted and error-prone methods to accomplish the task without resorting to indexing, though.

For instance,

>>> data = [[1,2,3],[4,5,6],[7,8,9]]
>>> data = [it[:-1] for it in data]
>>> data
[[1, 2], [4, 5], [7, 8]]
like image 100
molbdnilo Avatar answered Sep 27 '22 20:09

molbdnilo