Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to index nested lists in Python?

I have a nested list as shown below:

A = [('a', 'b', 'c'),
     ('d', 'e', 'f'),
     ('g', 'h', 'i')]

and I am trying to print the first element of each list using the code:

A = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
print A[:][0]

But I get the following output:

('a', 'b', 'c')

Required output:

('a', 'd', 'g')

How to get this output in Python?

like image 957
Tom Kurushingal Avatar asked Jul 08 '15 20:07

Tom Kurushingal


1 Answers

A[:] just creates a copy of the whole list, after which you get element 0 of that copy.

You need to use a list comprehension here:

[tup[0] for tup in A]

to get a list, or use tuple() with a generator expression to get a tuple:

tuple(tup[0] for tup in A)

Demo:

>>> A = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> [tup[0] for tup in A]
['a', 'd', 'g']
>>> tuple(tup[0] for tup in A)
('a', 'd', 'g')
like image 60
Martijn Pieters Avatar answered Oct 05 '22 10:10

Martijn Pieters