Comprehensions
List Comprehensions are usually considered an advanced topic, and most introductory programming students are not required to understand them despite their relative simplicity. However, they are very useful for preventing nesting and as situational alternatives to loops. When used properly, they can provide both readability and conciseness.
num_list = [1, 2, 3, 6, 8, 10, 50, 40, 35, 25, 27, 23, 93, 97, 104]
If you would like to create a list containing only the even numbers of another list, there are a few options:
You could use a for loop:
new_list = []
for num in num_list:
if num % 2 == 0:
new_list.append(num)
Which will result in new_list containing [2, 6, 8, 10, 50, 40, 104].
Alternatively, you could use a list comprehension:
new_list = [num for num in num_list if num % 2 == 0]
Which will result in new_list containing the same thing, but accomplished in one line.
There is a recurring format for list comprehensions which is as follows:
[expression for element in list if condition]
example_of_comp = [i*5 for i in range(50) if i % 2 != 0]
In the example above, i*5 is the expression, i is the element, and range(50) is the list. Conditionals can be added at the end of the comprehension in order to exclude or include particular values from the new list. The expression component, as previously mentioned, can be used to modify values once they are taken from the old list.
nested = [[1, 2, 3]] * 3
unnested = [num for seq in nested for num in seq]
The above is an example of a double list comprehension, where the first comprehension is used in the second comprehension. Nested comprehensions are also possible, but generally lack readability if nested beyond two layers.
nested_comp = [num % 65 for seq in [[x*2 for x in range(100)]]*5 for num in seq]
sum(nested_comp)
Understanding all that goes on in this list comprehension is nearly impossible thanks to its complicated one line nature. Nested list comprehensions shoudl generally be avoided— but in the end it is up to the developer.
def count_uppercase_chars_in_str(strings):
# Create a string containing each character in the file by combining each line using string.join()
valid_chars = "".join(strings)
# Create a list containing each character in the previous string, but removing non-uppercase chars
uppercase_chars = [char for char in valid_chars if char.isupper()]
# The length of the list of uppercase chars is the number of uppercase cars present in the file
number_of_chars = len(uppercase_chars)
return number_of_chars
strings = ["one", "two", "Three", "Four", "Five"]
charcount = count_uppercase_chars_in_str(strings)
print("There are %i uppercase characters in `strings`." % (charcount))
There are 3 uppercase characters in `strings`.
The syntax in this examples also hold true in the case of generator expressions, set comprehensions, etc. See the Iterators section for more information on generator expressions.