Functions Practice Problem

image

Screen Link:
https://app.dataquest.io/m/1012/python-fundamentals-practice-problems/10/finding-column-indexes

Can somebody explain why image was so important?

image
Why doesn’t this work?

Hi!
Being a list object it’s possible to iterate over the headers. In your code i is an element of the list (in other words it´s a column name), while in the solution code i is a number in range 0 to number of element in headers list. What´s the problem? You need to retrieve an element from header using headers[i]. But a list element can´t serve as an index, while the solution´s i do serve as an index.
Hope I´ve managed to explain it clear :grinning:

Because you are iterating the indexes of the list.

headers is a list containing string objects, if you want to get the index of every item in the list you’ll have to use enumerate function.

enumerate() adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops.

for i, header in headers:
    if headers[i] == col:
        index = i

Iterating individual items in header also works, you can get an index of an item in a list using the .index() method:

for header in headers:
    if header == col:
        index = headers.index(header)
1 Like