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]

1 Answers1

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953