Python language has a couple of methods for creating lists and dictionaries that are known
as comprehensions. There is also a third type of comprehension for creating a Python set, you will find that the comprehension constructs build on the knowledge you have acquired from the previous Ep's like The Noobs of Python: Ep.2.1 - List : Slice, Loops and more [Updated] as they contain loops and conditionals themselves.
Q: You've named a couple comprehensions, Which one are we going to start with?
A: Let's start with List Comprehensions !
List comprehensions are very useful. They can also be a bit hard to understand when and why you would use them. List comprehensions tend to be harder to read than just using a simple for
loop as well, feel free to review some of the examples in The Noobs of Python: Ep.2.1 - List : Slice, Loops and more [Updated] in case you need a refresher.
A list comprehension is basically a one line for
loop that produces a Python list data structure. List comprehensions evaluate an expression for each item in a list and return a list of the results. Think of this as a shortcut to apply an operation to every element in a list and get back a new list, without the pain of creating a temporary list. Here is an example fo a simple listcomp
:
>>> level1 = ['wendell', 'kreestuh', 'ryan']
>>> L1T = [i.capitalize() for i in level1]
>>> print(L1T)
['Wendell', 'Kreestuh', 'Ryan']
>>>
This is a simple example of iterating over the list and using the capitalize()
method to capitalize the list. By now we should be incorporating things we've learned in previous Ep's into our lessons for more practice. More of these in The Noobs of Python: Ep.3.0 - Methods to the Madness
Q: That was pretty simple but how is that broken down word by word?
A: Below is an example of the syntax for a basic list comprehension with some arguments aswell.
The most basic construction is [expression for var in list[for...|if...]]
. This means that you can have multiple for
and if
statements after the initial construction. Lets say you’re parsing a file and looking for a particular word, You could use a list comprehension pseudo-filter of sorts:
>>>if [i for i in line if "Word" in i]:
>>> do something
More examples in proceeding post below...
This is this initial post into List comprehensions to get the conversation going. There will be more post and examples moving us into Dict_Comps & Set_Comps in future Ep.3.x
Post your examples of List comps, or Parse out a text file using what you learn in The Noobs of Python: Ep.5.0 - File Manipulation by creating your own text file and using a list comp to filter words out.
Code_On_Code_Warrioirs