How Does This "[.. For .. In ..]" Work In Python?
Solution 1:
This list comprehension:
list_of_strings = [a.rstrip('\n') for a in list_of_strings]
is equivalent to this more generic code:
temp_list=[]
for a in list_of_strings:
temp_list.append(a.rstrip('\n'))
list_of_strings=temp_list
In most cases, a list comprehension is faster and easier to read. Learn it and use it if you want to write nontrivial Python.
Solution 2:
This takes a list of strings (stored in variable list_of_strings
), iterates through it assigning each string temporarily to variable a
each time through and strips the \n
character from each string. The result is a list of strings that is assigned back to the same variable.
This is using List Comprehension. Generally most for-loops and list operations involving append() can be converted to equivalent list comprehensions. Here's a simple example demonstrating this:
new_list = []
for i in range(10):
new_list.append(i**2)
could be rewritten simply as
new_list = [i**2 for i in range(10)]
You may find it instructive to take your list comprehension and rewrite it with a for
-loop to test your understanding (both should produce identical results).
In most cases, list comprehension is faster than the equivalent for
-loop and clearly a more compact way to express an algorithm. You can have nested list comprehensions too (just as you can have nested for
-loops), but they can quickly become hard to comprehend :)
Also, while not shown in the code above, you can filter values in the list comprehension, i.e., including them (or not) in the resulting list depending on whether they meet some criteria.
As an aside, Python also provides similar set comprehensions and generator expressions. It's well worth learning about all of these.
Solution 3:
Please read An Introduction to List Comprehensions in Python to get a better understanding of Python's list comprehension syntax.
Solution 4:
each iteration result doesn't write to the list, instead an entirely new list is created on the right hand side and then assigned to the variable list_of_strings on the left hand side of the = sign.
Solution 5:
This is a feature of Python called list comprehensions. Basically, what you write in the brackets is shorthand for 'do this loop and then create a list of the results'.
Post a Comment for "How Does This "[.. For .. In ..]" Work In Python?"