-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathList Comprehensions.py
More file actions
120 lines (48 loc) · 1.08 KB
/
List Comprehensions.py
File metadata and controls
120 lines (48 loc) · 1.08 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# list comprehensions are a unique way of creating a list in python
# if you fine creating list using .append() in loop
# than list comprehension is useful for you
# In[2]:
my_list = 'hello'
# In[3]:
mylist = []
for letter in my_list:
mylist.append(letter)
# In[4]:
mylist
# In[7]:
# best way is list comprehension
mylist = []
mylist = [letter for letter in my_list]
# In[8]:
# same thing
mylist
# In[9]:
myname = [x for x in 'uzair']
# In[10]:
myname
# In[11]:
num_array = [x for x in range(1,10,2)]
# In[12]:
num_array
# In[22]:
# with condition
# first x is a return value
num_array = [x for x in range(0,10,1) if x % 2 == 0]
# In[18]:
num_array
# In[27]:
# condition in both side
# but without x in first condition not running throw an error
num_array = [x if x<5 else '000' for x in range(0,10,1) if x % 2 == 0]
# In[28]:
num_array
# In[36]:
# nested list comprehensions
# solutuon of nested loop
nested = [x+y for x in [1,10,100] for y in [1,10,100]]
# In[37]:
nested
# In[ ]: