From the course: Python Essential Training

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

List comprehensions

List comprehensions

- [Instructor] Python has a really neat feature that's somewhat unique in programming languages, and that is the list comprehension. Note the word comprehension here has nothing to do with understanding but more to do with the word comprehensive, so systematically listing everything out. For example, my list is one, two, three, four, five. Let's write a list comprehension with this, two times item for item in my list. Isn't that neat? So square brackets surround the list comprehension and then there's a syntax frame much like the for loop that we saw before. So for item in my list. Of course item can be any variable name that you want. Just make sure that you use the same variable name over here when you're doing stuff with it. A list comprehension allows you to essentially make a for loop in one line while returning a copy of the list that you're iterating over. It also allows you to filter or call functions on every…

Contents