4. Building lists



Why would you ever use this:

evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50

As apposed to this:

evens_to_50 = range(0, 51, 2)
print evens_to_50


Honestly it doesn't really matter which way you do it as long as you get the same result. Both options are readable enough though one is elongated. Obviously the longer way has more functionality and can use operators to make more complicated lists, and it can handle floats unlike range().


Sometimes this:

is better than the other option. It really depends on the situation.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.