#100DaysOfCode in Python Transcripts
Chapter: Days 16-18: List comprehensions and generators
Lecture: Writing a simple list comprehension

Login or purchase this course to watch this video and the rest of the course contents.
0:00 List comprehensions and generators. Let's import the modules we are going to use. Let's start making a list of names. We've got a bunch of names
0:18 and let's loop over the names. for name in names and we're going to title case each name. There you go. Then let's do something more interesting
0:33 involving an if statement. So, let's keep the names that start with the first half of the alphabet.
0:40 An easy way to do that is to use the strings module, which has helpers like ascii.lowercase. So here, I used the strings ascii.lowercase,
0:56 I converted it into a list, and took a slice of the first 13 elements. Great, and the purpose, by the way, of this exercise
1:05 is to first do a classic for loop and if statement to later refactor that into a list comprehension. Right, so, Mike, Bob, Julian, Guitto,
1:25 but this seems a bit for both, right? We looked through the names, we do an if statement, and it takes like 5 lines of code.
1:34 Before we move on, I have to warn you though, if you see the elegance of list comprehensions, there is no way back and you want to use them everywhere,
1:41 and that's awesome because it reads like English and I don't know any reason why not to use them. Let's write a simple list comprehension
1:49 to do the same as I did here. The very basic level of this comprehension uses for inside the square brackets, so for name in names.
2:00 And before the for, just returns the name. So, this would just bounce the same list we had before and the nice thing then,
2:08 is that you can add an if statement after the list. So here, first character is in first half of the alphabet, that's got to stay
2:21 and a result, I want title cased, so I can do that here, and now we get the same result. So, if I call this new names2, I can say new_names asserted,
2:35 new_names equals new_names2, and they're exactly the same thing. So look at that, five lines of code, one line of code, and they read pretty well.
2:46 You just have to read from the inside out. Have a loop over the names. For every loop, I check this if statement and I return the name title case,
2:58 if that if statement is true. That's all there is to the basics of list comprehensions. You can nest them, but they might become unreadable,
3:07 so I would definitely stay at this level. The other way to write this is to use map and filter, like the functional programming construction Python,
3:17 and those work equally as well. Although, I find this more readable, this more like English. So, let's move on to another example.


Talk Python's Mastodon Michael Kennedy's Mastodon