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
  • 12,464
  • 7
  • 65
  • 73
Beginner
  • 2,643
  • 9
  • 33
  • 51

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
  • 39,665
  • 11
  • 104
  • 149
4

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
  • 19,069
  • 5
  • 54
  • 72