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 -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

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