[Tutor] List Comprehension Syntax
Malcolm Newsome
malcolm.newsome at gmail.com
Sun Dec 23 21:18:38 CET 2012
> Message: 4
> Date: Sun, 23 Dec 2012 02:48:42 -0500
> From: Mario Cacciatore <mariocatch at gmail.com>
> To: "tutor at python.org" <tutor at python.org>
> Subject: [Tutor] List Comprehension Syntax
> Message-ID: <50d6b74d.031d650a.3497.ffffad6a at mx.google.com>
> Content-Type: text/plain; charset="windows-1252"
>
> Hey everyone,
>
> I am having a very hard time understanding the list comprehension syntax.
I've followed the docs and could use some guidance from the fine folks here
to supplement my findings. If someone wouldn't mind replying back with an
example or two, with some explanation of each part I'd appreciate it.
> -------------- next part --------------
Here's an example that I used a list comprehension for when I was trying to
learn it.
I'd leave it to the tutors to say whether this is an appropriate use of it.
# search sorted array for integer k
def finder(list, k):
try:
s = sorted([int(i) for i in list])
k = int(k)
except ValueError:
print "Args must be ints. Your list arg was: {0} and your k arg was
'{1}'." .format(list, k)
return None
if k in s:
print "Index is: {0}".format(s.index(k))
else:
return -1
Hope it helps!
Malcolm Newsome
P.S. I hope the formatting is ok...I'm responding from my phone.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20121223/97d79364/attachment.html>
More information about the Tutor
mailing list