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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With