5

I have a list of lists which look like this:

[[[12, 15, 0], [13, 15, 25], [14, 15, 25], [16, 16, 66], [18, 15, 55]]]

What would be the best way to extract all elements occurring at index position 1. I know I can use a for loop like;

for i in list:
    for j in i:
        print j[2]

But is there a more "pythonic" (short /easy /less code/ efficient) way to do this?

Georgy
  • 9,972
  • 7
  • 57
  • 66
Beginner
  • 2,255
  • 8
  • 31
  • 49

2 Answers2

7

You can use a list comprehension:

>>> lst = [[[12, 15, 0], [13, 15, 25], [14, 15, 25], [16, 16, 66], [18, 15, 55]]]
>>> [x[1] for x in lst[0]]
[15, 15, 15, 16, 15]
>>>

The above is equivalent to:

lst = [[[12, 15, 0], [13, 15, 25], [14, 15, 25], [16, 16, 66], [18, 15, 55]]]
final_list = []
for sub_list in lst[0]:
    final_list.append(sub_list[1])

except that it is a lot more concise and also avoids all those calls to list.append (which means that it is more efficient).

Aran-Fey
  • 35,525
  • 9
  • 94
  • 135
2

use list comprehension:

[ x[1] for x in my_list[0] ]

this is more general if nested list is moree...

[ y[1] for x in my_list for y in x ]
Hackaholic
  • 17,534
  • 3
  • 51
  • 68