Can someone explain the answer

Screen Link:
https://app.dataquest.io/c/112/m/315/functions%3A-fundamentals/6/extract-values-from-any-column

What I expected to happen:
My Code:

opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)

def extract(index=apps_data[:4]):
    cols=[]
    for row in apps_data[1:]:
        col = row[index]
        cols.append(col)
    return cols

genres = extract(index=11)

What actually happened:

 CODE FROM THE PREVIOUS SCREEN
opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)

def extract(index):
    column = []    
    for row in apps_data[1:]:
        value = row[index]
        column.append(value)    
    return column

genres = extract(11)

Both are correct, but I don’t understand how the function’s paraeter ‘index’ knows the value I want.

Even the instructions say

  • Loop through the apps_data data set (excluding the header). Extract only the value you want by using the parameter (which will be an index number)

Hi,

Within the for loop, you instruct Python to loop through each row of apps_data (the dataset we are interested in), store the value we want from the column we are interested in (this is performed in value= row[index]), and append that value to the empty column we have created (this is what column.append(value)) does.

The variable value= row[index] defines to Python which column it should be looking for, as it is indexing the dataset here. Therefore, when running the function, you only need to provide Python with the column number, as it already knows that this number refers to a column index.

Hope that makes sense

1 Like

Thanks for clearing that up!

1 Like