Using for loops with lists:
Example:
list = [1,4,9,16,25]
sum = 0
for num in list:
sum += num
print (sum)
Output:
55
Using if loop with lists:
Example:
colors = ['red', 'blue', 'green']
if 'blue' in colors:
print ('blue color is available')
Output:
blue color is available
Using while loops with lists:
Example:
i = 0
a = [1,2,3,4,5,6,7,8,9]
while i < len(a):
print (a[i])
i = i + 3
Output:
1
4
7
list comprehension:
- Generating the elements into the list object by writing some logic in the list is known as a list-comprehension.
- in order to implement the list comprehension we need list object and for loop is mandatory.
- list comprehension with respect only mutable objects.
- comprehension is increase the performance of the application.
Example1:
x=[p for p in range(5)]
print(x)
Output:
[0, 1, 2, 3, 4]
Example2:
x=[p*p for p in range(5)]
print(x)
Output:
[0, 1, 4, 9, 16]
Example3:
x=[p**p for p in range(5)]
print(x)
Output:
[1, 1, 4, 27, 256]
Example4: print the even numbers only with-out comprehension.
y=[ ]
for p in range(10):
if p%2==0:
y.append(p)
print(y)
Output:
[0, 2, 4, 6, 8]
Example5: print the even numbers only with comprehension.
x=[p for p in range(10) if p%2==0]
print(x)
Output:
[0, 2, 4, 6, 8]
Example:
message="Hai Siva Krishna! How Are You"
words=message.split(" ")
requirement=[ [w.upper(),w.lower(),len(w)] for w in words]
for i in requirement:
print(i)
Output:
['HAI', 'hai', 3]
['SIVA', 'siva', 4]
['KRISHNA!', 'krishna!', 8]
['HOW', 'how', 3]
['ARE', 'are', 3]
['YOU', 'you', 3]
Example: matrix addition
x=[[1,1,1],[2,2,2],[3,3,3]]
y=[[1,1,1],[2,2,2],[3,3,3]]
result=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(x)):
for j in range(len(x[0])):
result[i][j]=x[i][j]+y[i][j]
for r in result:
print(r)
Output:
[2, 2, 2]
[4, 4, 4]
[6, 6, 6]
Example: matrix multiplication
x=[[1,1,1],[2,2,2],[3,3,3]]
y=[[1,1,1],[2,2,2],[3,3,3]]
result=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(x)):
for j in range(len(y[0])):
for k in range(len(y)):
result[i][j]+=x[i][k]*y[k][j]
for r in result:
print(r)
Output:
[6, 6, 6]
[12, 12, 12]
[18, 18, 18]
No comments:
Post a Comment