0

I am having trouble understanding why following works in Python. I would have never thought of creating list this way and yet I found method of composition using this construct. Why is this construct syntactically correct and how does the compiler resolve this statement?

>>> d= [int(4) for i in range(5)]
>>> d
[4, 4, 4, 4, 4]
2
  • 1
    int(4) is simply 4.
    – Maroun
    Nov 19, 2014 at 8:53
  • 1
    Martijn, the duplicate you linked to was also marked as a duplicate, by yourself :-) Nov 19, 2014 at 8:55

1 Answer 1

1

It's called list comprehension and, in this case, simply creates a list of elements, all with the integer value 4, for each of the items in the for section (the values 0 through 4 inclusive).

But int(4) is not really required, you can use 4 instead. However, even that's overkill for this particular situation, I'd prefer the more succinct:

[4] * 5

myself, leaving the for-loop form for more complicated stuff such as getting the cubes of odd numbers whose squares are less that a given value:

>>> [i**3 for i in range(99) if i*i < 99 and i%2 == 1]
[1, 27, 125, 343, 729]

Yes, a rather contrived example, but it shows how you can use list comprehensions to do some truly powerful stuff.

Not the answer you're looking for? Browse other questions tagged or ask your own question.