Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem in understanding Python list comprehensions

What does the last line mean in the following code?

import pickle, urllib                                                                                                                                                     

  handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p")
  data = pickle.load(handle)
  handle.close()

  for elt in data:
         print "".join([e[1] * e[0] for e in elt])

My attempt to the problem:

  • "".join... uses join -method to empty text
  • e[1] * e[0] multiplies two subsequent values in the sequence, e
  • I am not sure what is e
  • I am not sure, what it means, when you have something before for -loop, like: e[1] * e[0] for e in elt
like image 653
Léo Léopold Hertz 준영 Avatar asked Feb 01 '09 18:02

Léo Léopold Hertz 준영


2 Answers

Maybe best explained with an example:

print "".join([e[1] * e[0] for e in elt])

is the short form of

x = []
for e in elt:
  x.append(e[1] * e[0])
print "".join(x)

List comprehensions are simply syntactic sugar for for loops, which make an expression out of a sequence of statements.

elt can be an arbitrary object, since you load it from pickles, and e likewise. The usage suggests that is it a sequence type, but it could just be anything that implements the sequence protocol.

like image 76
Torsten Marek Avatar answered Sep 27 '22 19:09

Torsten Marek


Firstly, you need to put http:// in front of the URL, ie:

handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p")

An expression [e for e in a_list] is a list comprehension which generates a list of values.

With Python strings, the * operator is used to repeat a string. Try typing in the commands one by one into an interpreter then look at data:

>>> data[0]
[(' ', 95)]

This shows us each line of data is a tuple containing two elements.

Thus the expression e[1] * e[0] is effectively the string in e[0] repeated e[1] times.

Hence the program draws a banner.

like image 22
Andy Dent Avatar answered Sep 27 '22 18:09

Andy Dent