How to index nested lists in Python? -


i have nested list shown below:

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

and trying print first element of each list using code:

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

but following output:

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

required output:

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

how output in python?

a[:] creates copy of whole list, after element 0 of copy.

you need use list comprehension here:

[tup[0] tup in a] 

to list, or use tuple() generator expression tuple:

tuple(tup[0] tup in a) 

demo:

>>> = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')] >>> [tup[0] tup in a] ['a', 'd', 'g'] >>> tuple(tup[0] tup in a) ('a', 'd', 'g') 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -

Why does a .NET 4.0 program produce a system.unauthorizedAccess error on a Windows Server 2012 machine with .NET 4.5 installed? -