Skip to content

Commit cb1230f

Browse files
committed
list comprehension
1 parent 5ec2374 commit cb1230f

File tree

2 files changed

+316
-1
lines changed

2 files changed

+316
-1
lines changed

P-E-list comprehension.ipynb

+314
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,314 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"id": "b3c0145c",
6+
"metadata": {},
7+
"source": [
8+
"# Python: Everything\n",
9+
"- 27) **List comprehension** \n",
10+
" - Definition of a list comprehension\n",
11+
" - Example: to squares numbers in a list\n",
12+
" - Example: using if-clause to separate odd and even numbers of a list\n",
13+
" - Nested list comprehensions\n",
14+
" - Example: transposing a matrix or ordering a matrix in row major or column-major\n",
15+
" - Hint: loop control variables in list comprehensions are local\n",
16+
" - Example: dot product and Cartesian product of two lists\n",
17+
"<br>----------------------------------------------\n",
18+
"<br> https://www.pinterest.com/HamedShahHosseini/programming-languages/\n",
19+
"<br>https://github.com/ostad-ai/Python-Everything"
20+
]
21+
},
22+
{
23+
"cell_type": "markdown",
24+
"id": "35474859",
25+
"metadata": {},
26+
"source": [
27+
"**List comprehension:** is a concise way to create lists. We usually create new lists from some operations on the members of another iterable. We also may make a subsequence from the given iterable. An iterable could be a set, list, tuple, or etc.\n",
28+
"**The syntax:** is given below, which returns a new list without changing the original iterable.\n",
29+
"<br>$newlist=[expression\\; for\\; item\\; in\\; iterable\\; if\\; condition]$\n",
30+
"<br> We could use more if or for clauses."
31+
]
32+
},
33+
{
34+
"cell_type": "markdown",
35+
"id": "b1ade53a",
36+
"metadata": {},
37+
"source": [
38+
"Example below implements two ways to square numbers of a list: first with an ordinary function, the second is using list comprehension."
39+
]
40+
},
41+
{
42+
"cell_type": "code",
43+
"execution_count": 1,
44+
"id": "c819d4a6",
45+
"metadata": {},
46+
"outputs": [
47+
{
48+
"name": "stdout",
49+
"output_type": "stream",
50+
"text": [
51+
"Original list: [2, 3, 5, 7, 11]\n",
52+
"Squared list: [4, 9, 25, 49, 121]\n"
53+
]
54+
}
55+
],
56+
"source": [
57+
"mylist=[2,3,5,7,11]\n",
58+
"# doing the squares with list comprehension\n",
59+
"squares=[x**2 for x in mylist]\n",
60+
"print(f'Original list: {mylist}')\n",
61+
"print(f'Squared list: {squares}')"
62+
]
63+
},
64+
{
65+
"cell_type": "code",
66+
"execution_count": 2,
67+
"id": "0ca133a8",
68+
"metadata": {},
69+
"outputs": [
70+
{
71+
"name": "stdout",
72+
"output_type": "stream",
73+
"text": [
74+
"Original list: [2, 3, 5, 7, 11]\n",
75+
"Squared list: [4, 9, 25, 49, 121]\n",
76+
"Squared with list comprehension: [4, 9, 25, 49, 121]\n"
77+
]
78+
}
79+
],
80+
"source": [
81+
"# fucntion to square elements of list of numbers\n",
82+
"def square_x(xs):\n",
83+
" result=[]\n",
84+
" for x in xs:\n",
85+
" result.append(x**2)\n",
86+
" return result\n",
87+
"\n",
88+
"mylist=[2,3,5,7,11]\n",
89+
"squares=square_x(mylist)\n",
90+
"# doing the squares with list comprehension\n",
91+
"squares2=[x**2 for x in mylist]\n",
92+
"print(f'Original list: {mylist}')\n",
93+
"print(f'Squared list: {squares}')\n",
94+
"print(f'Squared with list comprehension: {squares2}')"
95+
]
96+
},
97+
{
98+
"cell_type": "markdown",
99+
"id": "b6165847",
100+
"metadata": {},
101+
"source": [
102+
"An example to separate odd and even numbers from a list using *if clause* in list comprehension."
103+
]
104+
},
105+
{
106+
"cell_type": "code",
107+
"execution_count": 3,
108+
"id": "b2c7aee2",
109+
"metadata": {},
110+
"outputs": [
111+
{
112+
"name": "stdout",
113+
"output_type": "stream",
114+
"text": [
115+
"Original list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]\n",
116+
"Even numbers of the list: [0, 2, 4, 6, 8, 10, 12, 14, 16]\n",
117+
"Odd numbers of the list: [1, 3, 5, 7, 9, 11, 13, 15, 17]\n"
118+
]
119+
}
120+
],
121+
"source": [
122+
"mylist=list(range(18))\n",
123+
"evens=[n for n in mylist if n%2==0]\n",
124+
"odds=[n for n in mylist if n%2!=0]\n",
125+
"print(f'Original list: {mylist}')\n",
126+
"print(f'Even numbers of the list: {evens}')\n",
127+
"print(f'Odd numbers of the list: {odds}')"
128+
]
129+
},
130+
{
131+
"cell_type": "markdown",
132+
"id": "5353c8ff",
133+
"metadata": {},
134+
"source": [
135+
"**Nested list comprehension:** An example to transpose a matrix with list comprehension. This time we use nested list comprehension."
136+
]
137+
},
138+
{
139+
"cell_type": "code",
140+
"execution_count": 4,
141+
"id": "f956e098",
142+
"metadata": {},
143+
"outputs": [
144+
{
145+
"name": "stdout",
146+
"output_type": "stream",
147+
"text": [
148+
"Original matrix: [[1, 2, 3], [4, 5, 6]]\n",
149+
"Transposed matrix: [[1, 4], [2, 5], [3, 6]]\n"
150+
]
151+
}
152+
],
153+
"source": [
154+
"matrix=[[1,2,3],[4,5,6]]\n",
155+
"transposed=[[row[i] for row in matrix] for i in range(len(matrix[0]))]\n",
156+
"print(f'Original matrix: {matrix}')\n",
157+
"print(f'Transposed matrix: {transposed}')"
158+
]
159+
},
160+
{
161+
"cell_type": "markdown",
162+
"id": "43996787",
163+
"metadata": {},
164+
"source": [
165+
"A example to flatten a nested list, here a matrix to **row-major order** and **column-major order**. We also use the function-based computation of these ordering to compare the results."
166+
]
167+
},
168+
{
169+
"cell_type": "code",
170+
"execution_count": 5,
171+
"id": "57c3787b",
172+
"metadata": {},
173+
"outputs": [
174+
{
175+
"name": "stdout",
176+
"output_type": "stream",
177+
"text": [
178+
"The matrix: [[1, 2, 3], [4, 5, 6]]\n",
179+
"row-major order: [1, 2, 3, 4, 5, 6]\n",
180+
"row-major order with list comrpehension: [1, 2, 3, 4, 5, 6]\n",
181+
"column-major order: [1, 4, 2, 5, 3, 6]\n",
182+
"column-major order with list comrpehension: [1, 4, 2, 5, 3, 6]\n"
183+
]
184+
}
185+
],
186+
"source": [
187+
"def row_major_order(matrix):\n",
188+
" result=[]\n",
189+
" for row in matrix:\n",
190+
" for col in row:\n",
191+
" result.append(col)\n",
192+
" return result\n",
193+
"\n",
194+
"def column_major_order(matrix):\n",
195+
" result=[]\n",
196+
" for col_index in range(len(matrix[0])):\n",
197+
" for row in matrix:\n",
198+
" result.append(row[col_index])\n",
199+
" return result\n",
200+
"\n",
201+
"matrix=[[1,2,3],[4,5,6]]\n",
202+
"# using list comprehensions\n",
203+
"row_major_lc=[element for row in matrix for element in row]\n",
204+
"column_major_lc=[row[i] for i in range(len(matrix[0])) for row in matrix]\n",
205+
"#---------------\n",
206+
"print(f'The matrix: {matrix}')\n",
207+
"print(f'row-major order: {row_major_order(matrix)}')\n",
208+
"print(f'row-major order with list comrpehension: {row_major_lc}')\n",
209+
"print(f'column-major order: {column_major_order(matrix)}')\n",
210+
"print(f'column-major order with list comrpehension: {column_major_lc}')"
211+
]
212+
},
213+
{
214+
"cell_type": "markdown",
215+
"id": "2530340e",
216+
"metadata": {},
217+
"source": [
218+
"**Attention:** *loop control variable* in list comprehension is **local**, so it does not change the variable with the same name outside of list comprehension."
219+
]
220+
},
221+
{
222+
"cell_type": "code",
223+
"execution_count": 6,
224+
"id": "079f2aa3",
225+
"metadata": {},
226+
"outputs": [
227+
{
228+
"name": "stdout",
229+
"output_type": "stream",
230+
"text": [
231+
"variable x before list comprehension: hello world\n",
232+
"result of list comrpehension: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
233+
"variable x after list comprehension: hello world\n"
234+
]
235+
}
236+
],
237+
"source": [
238+
"# a string variable\n",
239+
"x='hello world'\n",
240+
"print(f'variable x before list comprehension: {x}')\n",
241+
"N=10\n",
242+
"# x here is local variable\n",
243+
"xs=[x for x in range(N)]\n",
244+
"print(f'result of list comrpehension: {xs}')\n",
245+
"print(f'variable x after list comprehension: {x}')"
246+
]
247+
},
248+
{
249+
"cell_type": "markdown",
250+
"id": "f040af3e",
251+
"metadata": {},
252+
"source": [
253+
"We can implement **dot product**, and **Cartesian product** with list comprehension:"
254+
]
255+
},
256+
{
257+
"cell_type": "code",
258+
"execution_count": 7,
259+
"id": "7230fdf7",
260+
"metadata": {},
261+
"outputs": [
262+
{
263+
"name": "stdout",
264+
"output_type": "stream",
265+
"text": [
266+
"vector x: [1, 2, 3]\n",
267+
"vector y: [4, 5, 6]\n",
268+
"dot product x with y: 32\n",
269+
"Cartesian product x with y: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]\n"
270+
]
271+
}
272+
],
273+
"source": [
274+
"x=[1,2,3]\n",
275+
"y=[4,5,6]\n",
276+
"x_dot_y=sum([xi*yi for xi,yi in zip(x,y)])\n",
277+
"x_cartesian_y=[(xi,yi) for xi in x for yi in y]\n",
278+
"print(f'vector x: {x}')\n",
279+
"print(f'vector y: {y}')\n",
280+
"print(f'dot product x with y: {x_dot_y}')\n",
281+
"print(f'Cartesian product x with y: {x_cartesian_y}')"
282+
]
283+
},
284+
{
285+
"cell_type": "code",
286+
"execution_count": null,
287+
"id": "22275727",
288+
"metadata": {},
289+
"outputs": [],
290+
"source": []
291+
}
292+
],
293+
"metadata": {
294+
"kernelspec": {
295+
"display_name": "Python 3 (ipykernel)",
296+
"language": "python",
297+
"name": "python3"
298+
},
299+
"language_info": {
300+
"codemirror_mode": {
301+
"name": "ipython",
302+
"version": 3
303+
},
304+
"file_extension": ".py",
305+
"mimetype": "text/x-python",
306+
"name": "python",
307+
"nbconvert_exporter": "python",
308+
"pygments_lexer": "ipython3",
309+
"version": "3.8.10"
310+
}
311+
},
312+
"nbformat": 4,
313+
"nbformat_minor": 5
314+
}

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,5 @@
2525
23) Lambda expressions: We may use lambda keyword to define anonymous functions. Here, we define the syntax for lambda expressions, and then we bring some applications.
2626
24) Magic methods, __getitem__ and __setitem__: We review getitem and setitem methods that may be used for **indexing** and **assignment** on instances of a class, respectively.
2727
25) Iterators and iterables: We use iterators to iterate over iterables. This section reviews both of them. Lists, sets, tuples, and dictionaries are examples of iterables.
28-
26) Callable objects: We can make a class callable by defining a method in the class named **__class__**. This way, any instance of the class can be called like a function.
28+
26) Callable objects: We can make a class callable by defining a method in the class named **--class--**. This way, any instance of the class can be called like a function.
29+
27) List comprehension: We may use list comprehension to create lists from another lists or any iterables in a concise way. A list comprehension may include for-loops and if-clauses.

0 commit comments

Comments
 (0)