<iterator>.append() I dont get the logic

Hi everyone

During the fundamentals python missions you come across a couple of missions where you need to append a label to the data set (apps_data) in a new column using a for loop.
Afterwards you have to append a column name to the data set.

In the for loop you have to append the label to the iterator (app)?? And then the labels are apparently appended to the apps_data when the loop has run.
I would think you should append it to the apps_data during the looping.

Example:

for app in apps_data[1:]:
price = float(app[4])

if price == 0.0:
    app.append('free')
else:
    app.append('non-free')

apps_data[0].append(‘free_or_not’)

Can someone explain the logic or what I am missing?

Thanks

Probably the author of the mission could explain better. My understanding is that this could be done with purpose, so that you know how to add columns and column names for your own projects later.

I don’t get it either. So if someone could still explain it?

My first try was with app_data[1:].append instead of app.append.

Hi @DataBuzzer, I’ll try my best! Remember that apps_data is a list of lists, so that every row of the dataset is a separate list. In the loop, we’re taking one row at a time (which is a list), and adding either free or non-free to the end of every row. If you can mentally picture all the rows in a grid, the visual result of adding a new item to the end of every row will end up being the creation of a new column.

Hello @kasperbirkelund, @DataBuzzer,

I hope this will help clear your doubts.
Consider the following snippet of code :

iterable_list_of_lists = [
        [1,2,3,4],
        [2,4,6,8],
        [3,6,9,12],
        [4,8,12,16]]

for iterator_is_a_row_pointer_to in iterable_list_of_lists:
    '''Another variable `iterator`,
       points to the same row pointed to by iterator_is_a_row_pointer_to
    '''
    iterator = iterator_is_a_row_pointer_to

    ''' Both `iterator` and `iterator_is_a_row_pointer` point to the current row
    '''
    iterator.append(iterator[-1] + iterator[0])
    iterator_is_a_row_pointer_to.append(iterator_is_a_row_pointer_to[-1] + iterator_is_a_row_pointer_to[0])

print(iterable_list_of_lists)

Output:
[[1, 2, 3, 4, 5, 6], [2, 4, 6, 8, 10, 12], [3, 6, 9, 12, 15, 18], [4, 8, 12, 16, 20, 24]]

What you are appending to is to a pointer to the current row of iterable_list_of_lists in each iteration.

So you are essentially achieving apps_data[0].append('text') through app.append('text')

1 Like

Thanks for answering. I starts to make sense now!

Thanks for your response!