Adv. Topics in Python - Module 4. Building Lists


Building Lists Exercise

Could someone provide an explanation (or even a link) to the following syntax:

I don't understand why we use i for i in instead of starting off with for i in. I understand how the for loop works, but I don't understand why is it that we need an "i" before "for" in this case.


This is a list comprehension where the list is built from the inside, without appending.

The value of i before for i is the value that gets added to the list. Take a look at the regular code your expression replaces:

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

For practice, it is good to be able to work comprehensions back into inline code, and vice versa, work inline code into a comprehension. There are also comprehensions for dictionaries.

We can play with these for hours, and some of our concoctions, while they may work marvelously, can become unreadable, so hard to debug. Balance in code design is important, but for just the sheer fun, go to town on these in your practice time.


I see. Instead of "appending" at the end of the for loop, it "adds" the value in the beginning upon calculation of for loop and if statement.

Couldn't have asked for a better explanation!


Precisely. The value is added conditionally, but all possible values are iterated over.

Picture the list being built one value at a time. At the start, the logic is all that is inside the brackets. As it iterates over truthy values, those values are placed to the left of the logic which shifts over. Once completed iterating, the logic is removed from the structure leaving a finished list. I say picture because it probably is not done that way, exactly.

Metaphorically, think of an earth worm tunneling its way through the soil, pooping as it goes. Our logic is leaving droppings as it works through the range of values.


Yea definitely, I can imagine a machine just spitting out True values to the "left" into a bucket--in this case saving to a list instead of a bucket. Makes sense. I've never seen something similar in the past. It's certainly an interesting method.


What's more, just as we can nest logic in our inline code, we can nest logic in a comprehension. This is where is gets wonky real fast so keep your production designs as real and maintainable as you can, but never be afraid to stretch the envelope for experimentation of one-off code situations where you just want a solution real quick.


Say we want a list of just the even numbers that are divisible by 3. Do we build a list of even numbers then trial divide by 3? Or do will build a list by 3's and trial divide by 2?

It looks to me that we could do either but our comprehensions will look a bit different from one another.

by_threes = [ x for x in range(100) if x % 3 == 0 ]

Now I see this is a terrible example. If all we want is a list by threes,

by_threes = range(3, 100, 3)

will give us that. That means we can just modify the range in your example and get the achieved result. But let's work with the exaggerated approach anyway, for the fun of it.

even_by_three = [y for y in [x for x in range(100) if x % 3 == 0] if y % 2 == 0]

Cool stuff, eh?

Think of range(100) as being an actual list that is supplied to our program with no particular order or size. That 's where the above comprehension would prove useful because there is no predictibily of the inputs.


I can see how that can get messy real quick. That's a great example. It seems to be a life saver at times, but a real antagonist if not kept in check. The applicability is just fun, though.

Debugging one of those in someone else's code would make me really sad :sweat_smile:


Off topic

Let's go all out and pretend that we have designed a communication system that uses only 6 letters, a, b, c, d, e and f. We add those letters in plain sight, inside hex values which are converted to decimal when encoding. To decode we would convert the decimal to hexadecimal then strip all the digits and keep the letters. Now the letters could be a predetermined codex or lexicon where two and three letter combinations are a word or phrase. We would need a table that defines the lexicon but not much else.

There are 30 permutations in 6P2 and 120 in 6P3 giving 150 possible terms or phrases in our code (that is if I haven't flubbed the math, you get the picture, though). See if you can come up with a way to encode and decode using comprehensions.


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