Jason
Jason

Reputation: 39

How to loop over a list of lists

Recently I have come up with using a for loop to reform a list.

First, I did this:

list1 = [[1],[2],[3]]
list2 = []
for x in list1:
    list2.append(x)
print(list2)

And the output was:

[[1], [2], [3]]

Then, I tried:

list2 = []
for x in list1:
    list2.append(x[0])

And the output was:

[1, 2, 3]

Could someone please explain to me what x[0] does in this for loop? I thought this index would mean only taking the first element in a list.

Upvotes: 0

Views: 1528

Answers (5)

marianoju
marianoju

Reputation: 346

Could you please tell what does "x[0]" do in this for loop; I thought this index would mean only taking the first element in a list.

list1 = [[1],[2],[3]] is not simply a list but a list of lists. Every element of list1 is a list – albeit with only one sub-element. So you are effectively iterating over every list within your list list1, picking the first element at position 0 (which is all there is) and appending it to your new list list2.

Upvotes: 1

Harsha Biyani
Harsha Biyani

Reputation: 7268

You are iterating list containing list. e.g :

a = [[1], [2], [3]]
a[0] will contain list [1] #i.e it is containing list
a[1] will contain list [2] 
a[2] will contain list [3]

If you are want to access contents from list of list, you have to pass 2 indexes. e.g :

a[0][0] will contain 1 #i.e it is containing element
a[1][0] will contain 2
a[2][0] will contain 3

You also can try extend keyword to achieve the same. The extend() method takes a single argument (a list) and adds it to the end.

list1 = [[1],[2],[3]]
list2 = []
for x in list1:
    list2.extend(x)
print(list2)

Upvotes: 0

vash_the_stampede
vash_the_stampede

Reputation: 4606

list1 = [[1], [2], [3]]

for x in list1:
    list2.append(x[0])

Okay lets just look at what we are doing here:

for x in list1:

Well x in this loop will represent [1], [2], [3] which are list containing a certain number in the 0 position.

A little more perspective lets look at it like this:

list1[0][0] = 1

list1[1][0] = 2

list1[2][0] = 3

Upvotes: 0

m4p85r
m4p85r

Reputation: 402

When you go

for x in list1:

and print out x you'll get:

>[1]
>[2]
>[3]

Because each element in list1 are still lists! The lists only have one element but they're still stored within a list. When you use x[0] you're telling Python you want to access the first element of each list, which is the number you want.

Also another thing you could do which would be faster than a for loop is to use list comprehension:

 list2 = [x[0] for x in list1]

Upvotes: 0

blhsing
blhsing

Reputation: 106455

x[0] returns the item at index 0 of the list x, so by appending to a new list with x[0] in your for loop, you are appending the value within the sub-list rather than the sub-list itself, thereby achieving the effect you want, flattening the list.

Upvotes: 1

Related Questions