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
Post a Comment