Re: [Tutor] List Comprehension Syntax

2012-12-23 Thread Mitya Sirenef

On 12/23/2012 02:48 AM, Mario Cacciatore wrote:

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.



Hi Mario, here are some examples (using python3 but very similar in py2.7):


L = range(20)

 [x for x in L]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]


[x for x in L if  x=10]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


[(x,x) for x in L]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), 
(9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 
16), (17, 17), (18, 18), (19, 19)]



[x*2 for x in L]

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]


[(x, x*3) for x in L if  x=10]
[(0, 0), (1, 3), (2, 6), (3, 9), (4, 12), (5, 15), (6, 18), (7, 21), (8, 
24), (9, 27), (10, 30)]



def strmul(x): return  str(x), x*2

...


[strmul(x) for x in L  if x=10]
[('0', 0), ('1', 2), ('2', 4), ('3', 6), ('4', 8), ('5', 10), ('6', 12), 
('7', 14), ('8', 16), ('9', 18), ('10', 20)]




Hope this helps!


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List Comprehension Syntax

2012-12-23 Thread Alan Gauld

On 23/12/12 07:48, Mario Cacciatore wrote:


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.



You could try reading the List Comp sub-section of the Functional 
Programming topic in my tutorial.


That has several examples with explanations and equivalent code etc.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List Comprehension Syntax

2012-12-23 Thread Peter Otten
Mario Cacciatore wrote:

 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.

Consider

[c.lower() + x % 3 * c for x in range(10) if x not in [7,8] for c in aBcDE 
if c.isupper() if c != B]

That looks complex! So let's take it apart. Here's the cheat-sheet:

result = [expr(x) for x in items]

is equivalent to a for-loop:

result = []
for x in items:
result.append(expr(x))

The expression on the left of the list-comp moves into the (innermost if 
there is mor than one) loop.

result = [expr(x) for x in items if cond(x)]

is equivalent to

result = []
for x in items:
if cond(x):
result.append(expr(x))

You can add an arbitrary number of conditions:

result = [expr(x) for x in items if cond1(x) if cond2(x) if cond3(x)]

is equivalent to

result = []
for x in items:
if cond1(x):
if cond2(x):
if cond3(x):
result.append(expr(x))

You can also have multiple 'for' clauses:

result = [expr(x, y, z) for x in items1 for y in items2 for z in items3]

is equivalent to

result = []
for x in items1:
for y in items2:
for z in items3:
result.append(expr(x, y, z))

Now back to our initial example. Let's reformat it a bit

result = [
c.lower() + x % 3 * c  # that's expr(x, c)
for x in range(10) 
if x not in [7,8] 
for c in aBcDE 
if c.isupper() 
if c != B
]

That looks quite similar to

result = []
for x in range(10) :
if x not in [7,8]:
for c in aBcDE:
if c.isupper():
if c != B:
result.append(c.lower() + x % 3 * c)

Whenever you encounter a list comprehension you don't understand immediately 
you can easily translate it into for-loops and if-statements, either by 
reformatting in an editor or in your mind. Similarly you can convert for-
loops appending to a list into a list comprehension. Can you spell

result_loop = []
for x in range(10):
for y in range(10):
if (x + y) % 2:
result_loop.append((x, y))

as a list-comp? Copy the above twice and apply the reverse reformatting 
trick to the second copy.

result_listcomp = [...] # your code
assert result_loop == result_listcomp, Something went wrong, try again
print(success)

If you run the script it should print 'success'.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List Comprehension Syntax

2012-12-23 Thread Steven D'Aprano

On 23/12/12 18:48, Mario Cacciatore wrote:

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.



If you did mathematics in high school, you may remember set-builder notation:

http://en.wikipedia.org/wiki/Set-builder_notation

There are a number of variations of this notation, depending on how formal
you want to be. For example:

{3x+1 ∀ x ∈ {1, 2, 3}}

This says:

build the set of values 3 times x plus 1, for all x values that are elements
of the set {1, 2, 3}

and it would produce the values:

x=1 - 3*1 + 1
x=2 - 3*2 + 1
x=3 - 3*3 + 1}

giving the final set {4, 7, 10}


Python uses similar notation, except based on English words instead of
mathematical symbols. In Python, we generally use lists or tuples, not sets,
so the list comprehension would be:

[3*x + 1 for x in (1, 2, 3)]


We can pull this apart to see what each part does.

[ ]

  The square brackets build a list.

3*x + 1

  This is the list comprehension expression. It is evaluated each time
  the list comp goes through the loop.

for x in (1, 2, 3)

  This sets up the list comprehension loop, and defines the loop
  variable, just like a for-loop. The tuple (1, 2, 3) is the loop
  sequence, x takes each value from this in turn.


So this list comprehension is equivalent to this for-loop:


tmp = []
for x in (1, 2, 3):
   tmp.append(3*x + 1)



except that you don't need to define a temporary list to accumulate the
results, the list comprehension does that for you.


List comprehensions can be more complicated. They can also take one or
more if clause:


[2*n for n in range(10) if n%2 == 1]


is equivalent to this for-loop:

tmp = []
for n in range(10):
if n%2 == 1:
tmp.append(2*n)



and so it will produce the list:

[2, 6, 10, 14, 18]


Naturally, you can use any sequence or iterable in the for-loop
part of list comps:

myname = Quentin
[c for c in myname if c.lower() != q if c.upper() != T]


will give

['u', 'e', 'i', 'n']


The sequence can even be another list comprehension:


[y+1 for y in [2*x for x in (1, 2, 3)] if y  5]


gives [3, 5], and is equivalent to this pair of loops:


tmp1 = []
tmp2 = []
for x in (1, 2, 3):
tmp1.append(2*x)
for y in tmp1:
if y  5:
tmp2.append(y+1)



List comps can also take multiple loops:

[(a, b) for a in range(3) for b in range(3)]


gives this result:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]


and is equivalent to this nested loop:


tmp = []
for a in range(3):
for b in range(3):
tmp.append( (a, b) )



List comprehensions are powerful and compact, but because they are so compact,
they can also be hard to read. Resist the temptation to write every for-loop
as a list comprehension! Keep your list comps simple, and you will not regret
it. Nobody has ever said, I wish my list comprehensions were more complicated
and hard to read!



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List Comprehension Syntax

2012-12-23 Thread Malcolm Newsome
 Message: 4
 Date: Sun, 23 Dec 2012 02:48:42 -0500
 From: Mario Cacciatore marioca...@gmail.com
 To: tutor@python.org tutor@python.org
 Subject: [Tutor] List Comprehension Syntax
 Message-ID: 50d6b74d.031d650a.3497.a...@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.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List Comprehension Syntax

2012-12-22 Thread Mario Cacciatore
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. ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor