-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp9.py
More file actions
143 lines (63 loc) · 2.5 KB
/
p9.py
File metadata and controls
143 lines (63 loc) · 2.5 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# List Comprehension (uniq and important topic in python)
# with the help of list comprehension we can create of list in one line
# ex--> create a list of squares from 1 to 10
square1=[]
for i in range(1,11):
square1.append(i**2)
i=i+1
print(square1) # o/p: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# OR
square2=[j**2 for j in range(1,11)]
print(square2) # o/p: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# ex----> create list of negative number 1-10
neg_num=[-i for i in range(1,11)]
print(neg_num) # o/p: [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
# OR
neg1_num=[]
for i in range(1,11):
neg1_num.append(-i)
print(neg1_num) # o/p: [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
# Ex
names=['Ravin','Rupen','Yash','Chirag']
new_list=[]
for name in names:
new_list.append(name[0])
print(new_list) # o/p: ['R', 'R', 'Y', 'C']
# oR
new_list=[name[0] for name in names]
print(new_list) # o/p: ['R', 'R', 'Y', 'C']
# Excercise 1
list1=['abc','def','klp','asd']
rev_list=[rev[::-1] for rev in list1]
print(rev_list) # o/p: ['cba', 'fed', 'plk', 'dsa']
# list comprehension with if statement
numbers=list(range(1,11))
print(numbers) # o/p: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_num=[]
for i in numbers:
if i%2==0:
even_num.append(i)
print(even_num) # o/p: [2, 4, 6, 8, 10]
# OR
eve_list=[i for i in numbers if i%2==0]
print(eve_list) # o/p: [2, 4, 6, 8, 10]
odd_list=[i for i in range(1,11) if i%2!=0]
print(odd_list) # o/p: [1, 3, 5, 7, 9]
# Exercise 2
def int_to_str(l1):
return [str(i) for i in l1 if type(i)==int or type(i)==float]
print(int_to_str([True,False,'Str',[1,2,3],1,1.0,2])) # o/p: ['1', '1.0', '2']
# list comprehension with if-else statement
num1_list=[]
for i in range(1,11):
if i%2==0:
num1_list.append(-i)
else:
num1_list.append(i**2)
print(num1_list) # o/p: [1, -2, 9, -4, 25, -6, 49, -8, 81, -10]
num_list=[-i if (i%2==0) else i**2 for i in range(1,11) ]
print(num_list) # o/p: [1, -2, 9, -4, 25, -6, 49, -8, 81, -10]
# Nested list comprehension
# Example---->[[1,2,3],[1,2,3],[1,2,3]]
nested_list=[[i for i in range(1,4)] for j in range(1,4)]
print(nested_list) # o/p: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]