Skip to content

Commit b50845d

Browse files
committed
Add list comprehensions
1 parent 23d0c4e commit b50845d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

chapters/lists.tex

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,45 @@ \section{Exercises with lists}
4747
\item Remove the sublist [4, 9].
4848

4949
\end{enumerate}
50+
51+
52+
\section{List comprehensions}
53+
54+
List comprehensions are a concise way to create lists. It consists of square brackets containing an expression followed by the "for" keyword. The result will be a list whose results match the expression. Here's how to create a list with the squared numbers of another list.
55+
56+
\begin{lstlisting}
57+
>>> [x*x for x in [0, 1, 2, 3]]
58+
[0, 1, 4, 9]
59+
\end{lstlisting}
60+
61+
Given its flexibility, list comprehensions generally make use of the "range" function which returns a range of numbers:
62+
63+
\begin{lstlisting}
64+
>>> [x*x for x in range(4)]
65+
[0, 1, 4, 9]
66+
\end{lstlisting}
67+
68+
Sometimes you may want to filter the elements by a given condition. The "if" keyword can be used in those cases:
69+
70+
\begin{lstlisting}
71+
>>> [x for x in range(10) if x % 2 == 0]
72+
[0, 2, 4, 6, 8]
73+
\end{lstlisting}
74+
75+
The exemple above returns all even values in range 0..10. More about list comprehensions can be found at \url{https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions}.
76+
77+
\section{Exercises with list comprehensions}
78+
79+
\begin{enumerate}
80+
81+
\item Using list comprehensions, create a list with the squares of the first 10 numbers.
82+
83+
\item Using list comprehensions, create a list with the cubes of the first 20 numbers.
84+
85+
\item Create a list comprehension with all the even numbers from 0 to 20, and another one with all the odd numbers.
86+
87+
\item Create a list with the squares of the even numbers from 0 to 20, and sum the list using the "sum" function. The result should be 1140. First create the list using list comprehensions, check the result, then apply the sum to the list comprehension.
88+
89+
\item Make a list comprehension that returns a list with the squares of all even numbers from 0 to 20, but ignore those numbers that are divisible by 3. In other words, each number should be divisible by 2 and not divisible by 3. Search for the "and" keyword in the Python documentation. The resulting list is [4, 16, 64, 100, 196, 256].
90+
91+
\end{enumerate}

0 commit comments

Comments
 (0)