Store nested list elements


#1



Hi. What I am asking is not from codeacademy exercises but from tinkering through basic of python.
First off, I wanted to iterate through a list inside a list and store every second element into a new list. I have tried it like this.

nested = [[1, 2], [3, 4], [5, 6], [6, 7], [8, 9]]
new = []
for each in nested[:][:1]:
    new.append(each)
print (new)


The output that I got is this : [[1, 2]]
and I expected to get only one list, "new" that contains 2,4,6,7,9 (only 1 square brackets)


#2

i am not sure how you expected this to work, here is what i would do:

nested = [[1, 2], [3, 4], [5, 6], [6, 7], [8, 9]]
new = []
for each in nested:
    new.append(each[1])
print (new)

why does this work? you loop over nested, so each will now hold the nested list ([1,2], then in the next run [3,4] and so on), we can see this:

nested = [[1, 2], [3, 4], [5, 6], [6, 7], [8, 9]]
new = []
for each in nested:
    print(each)
    new.append(each[1])
print (new)

then we can append each[1] to new. we use 1, since that seems to be the index you want to retrieve from the nested list, using slice (like you did) would give a list in return.

the way your loop was constructed, also only looped over the first nested list


#3

You are right. The whole time I was thinking of slicing through a nested list. Retrieving index is the answer, thank you!


#4

also take a close look at how i constructed the loop, it is very different from yours


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.