1) Find max, second max from a given list
l1 = [100,28,46,78]
max = l1[0]
for i in l1:
if i > max:
max = i
print(max)
l1 = [28,46,78,100]
max = l1[0]
second_max = 0
for i in l1:
if i >= max:
second_max = max
max = i
print(second_max)
Output:
100
78
2) Find min, second min from a given list
l1 = [100,28,46,78]
min = l1[0]
for i in l1:
if i <= min:
min = i
print(min)
l1 = [100,46,78,28]
min = l1[0]
second_min = 0
for i in l1:
if i <= min:
second_min = min
min = i
print(second_min)
Output:
28
46
3) Reverse a list without using reverse()
l1 = [100,28,48,69]
rev = []
i = len(l1)-1
while i>=0:
rev.append(l1[i])
i-=1
print(rev)
Output:
[69, 48, 28, 100]
4) Confirm if a given list is palindrome or not:
l1 = [10,20,30,20,10]
l2 = l1[::-1]
print(l1==l2)
Output:
True
5) Remove duplicate elements from a list:
l1 = [10,20,30,20,10]
l2 = []
for i in l1:
if i not in l2:
l2.append(i)
print(l2)
Output:
[10,20,30]
6) Find pairs with a given sum:
sumval = 6
pair = []
l1 = [1,5,2,4,3,7,8,6,0]
for i in range(len(l1)):
for j in range(i+1,len(l1)):
if l1[i]+l1[j] == 6:
pair.append((l1[i],l1[j]))
print(pair)
Output:
[(1, 5), (2, 4), (6, 0)]
isinstance():
isinstance() is a built-in function used to check if an object belongs to a specific class, type, or a subclass of that class.
7) Print only str elements from a given list:
l1 = [10,20,True, False, 5.4, 'abcd', 'pqrs']
for i in l1:
if isinstance(i,str):
print(i)
Output:
abcd
pqrs
8) Find the missing number in a list of 1 to n:
l = [1,2,3,4,5,6,8,9,10]
i = 0
j = 1
while i<len(l)-1:
if l[j]-l[i] == 1:
pass
else:
print(l[j]-1)
i+=1
j+=1
Output:
7
9) Nested List: Flattening a nested list:
def flatten_list(l):
flat = []
for i in l:
if isinstance(i,list):
flat.extend(flatten_list(i))
else:
flat.append(i)
return flat
nested_list = [1, [2, [3,4], 5], 6]
print(flatten_list(nested_list))
Output:
[1,2,3,4,5,6]
Top comments (0)