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