-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGUIDE_list_comprehension.py
More file actions
80 lines (56 loc) · 2.19 KB
/
GUIDE_list_comprehension.py
File metadata and controls
80 lines (56 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# author: Asmaa ~ 2019
# LIST COMPREHENSION IN PYTHON
# ----------------------------------------------
# definition: An elegant way to define and create lists based on existing lists.
# General Syntax: [expression for item in list]
name = 'Asmaa'
name_letters = [l for l in name]
print('List of letters:', type(name_letters), name_letters)
# Output: <class 'list'> ['A', 's', 'm', 'a', 'a']
# Conditions in list comprehension
# Syntax: [expression for item in list if condition]
ages = [5, 6, 28, 13, 18, 12, 11, 3, 44, 38, 60, 25, 21, 70]
adults = [age for age in ages if age >= 18]
print('Adults:', adults)
# Output: [28, 18, 44, 38, 30, 25, 21]
# Nested if with list comprehension
# Syntax: [expression for item in list if condition if conditions]
youth = [age for age in ages if age >= 18 if age <= 40]
print('Youth:', youth)
# OR
# Syntax: [expression for item in list if condition and conditions]
youth = [age for age in ages if age >= 18 and age <= 40]
print('Youth:', youth)
# if-else with list comprehension
# Syntax: [expression if condition else expression for item in list]
classes = ['adult' if age >= 18 else 'Child' for age in ages]
print('Classes:', classes)
# Output: ['Child', 'Child', 'adult', 'Child', 'adult', 'Child', 'Child',
# 'Child', 'adult', 'adult', 'adult', 'adult', 'adult', 'adult']
# Nested for loops
# General Syntax: [expression outer loop inner loop]
# Detailed Syntax: [expression for expression2 in list for expression in expression2]
# unpack the matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
unpacked = [item for row in matrix for item in row]
print('Unpacked Matrix:', unpacked)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# ----------------------------------------------------------------------
# example - 0:
num = [1, 2, 3, 4, 5]
square = [num**2 for num in num]
print('Squares:', square)
# Output: [1, 4, 9, 16, 25]
# example - 1:
height = [10, 20, 30, 40]
width = [1, 2, 3, 4]
area = [h*w for h, w in zip(height, width)]
print('Areas:', area)
# Output: [10, 40, 90, 160]
# example - 2:
# get all possible combinations
str1 = 'abc'
str2 = 'xyz'
comb = [j + k for j in str1 for k in str2]
print('Combinations:', comb)
# Output: ['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']