[Tutor] what's a concise way to print the first elements in a
nested list
Orri Ganel
singingxduck at gmail.com
Thu Jan 13 02:19:11 CET 2005
Danny Yoo wrote:
>On Wed, 12 Jan 2005, Orri Ganel wrote:
>
>
>
>> >>> stuff = [[0,'sdfsd','wrtew'], [1, 'rht','erterg']]
>> >>> stuff
>>[[0, 'sdfsd', 'wrtew'], [1, 'rht', 'erterg']]
>> >>> print [stuff[i][0] for i in range(len(stuff))]
>>[0, 1]
>>
>>
>
>
>Hi Orri,
>
>An alternative way to write this is:
>
>###
>print [row[0] for row in stuff]
>###
>
>which extracts the first element out of every "row" sublist in 'stuff'.
>
>
>Best of wishes!
>
>
>
>
True. The only difference is the use of "for i in range(len(...))"
instead of "for i in ...". I suppose either works, but since Python
only allows you to edit the elements of a sequence using the "for i in
..." notation (and have the changes stick) inside of a list
comprehension (and perhaps a generator, as well, I don't know), I try to
stay away from it so I don't get confused when it doesn't work outside
of one.
Cheers,
Orri
--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050112/744d72d7/attachment.htm
More information about the Tutor
mailing list