Here you go — short and snappy Python code for all 15 problems.
Efficiency level: maxed out 💯
1. Sum Items in List
print(sum([1, 2, 3]))
2. Multiply Items in List
from math import prod; print(prod([1, 2, 3, 4]))
3. Get Largest Number in List
print(max([1, 2, 3, 99]))
4. Get Smallest Number in List
print(min([1, 2, -3, 0]))
5. Count Strings with Same Start and End
print(sum(s[0]==s[-1] for s in ['abc','xyz','aba','1221'] if len(s)>1))
6. Sort Tuples by Last Element
print(sorted([(2,5),(1,2),(4,4),(2,3),(2,1)], key=lambda x: x[-1]))
7. Remove Duplicates from List
print(list(set([1,2,2,3,1])))
8. Check if List is Empty
print([] == [])
9. Clone or Copy a List
a = [1,2,3]; b = a[:]; print(b)
10.Find Words Longer Than n
print([w for w in ['hi','hello','world'] if len(w)>3])
11.Check Common Member Between Two Lists
print(bool(set([1,2]) & set([2,3])))
12.Remove Specific Elements from List
l = ['Red','Green','White','Black','Pink','Yellow']
print([v for i,v in enumerate(l) if i not in (0,4,5)])
13.Generate 3D Array
print([[['*']*6 for _ in range(4)] for _ in range(3)])
14.Remove Even Numbers from List
print([x for x in [1,2,3,4,5] if x%2])
15.Shuffle List
import random; l = [1,2,3]; random.shuffle(l); print(l)
16. Generate Square Numbers in Range
s = [x*x for x in range(1,31) if x*x <= 30]; print(s[:5]+s[-5:])
17. Check If All Numbers Are Prime
is_prime = lambda x: x > 1 and all(x%i for i in range(2, int(x**0.5)+1))
print(all(is_prime(i) for i in [3, 5, 7, 13]))
18. Generate All List Permutations
from itertools import permutations; print(list(permutations([1,2,3])))
19. Calculate Difference Between Lists
print(list(set([1,2,3])-set([2,3,4])))
20. Access List Indices
[print(i,v) for i,v in enumerate(['a','b','c'])]
21. Convert List to String
print(''.join(['H','e','l','l','o']))
22. Find Index of List Item
print(['a','b','c'].index('b'))
23. Flatten Shallow List
print([i for sub in [[1,2],[3,4]] for i in sub])
24. Append One List to Another
a = [1,2]; b = [3,4]; a += b; print(a)
25. Select Random Item from List
import random; print(random. Choice([1,2,3,4]))
26. Check Circularly Identical Lists
a, b = [1,2,3], [2,3,1]; print(''.join(map(str,b)) in ''.join(map(str,a*2)))
27. Find Second Smallest Number in List
print(sorted(set([1,2,3,1]))[1])
28. Find Second Largest Number in List
print(sorted(set([1,2,3,4]))[-2])
29. Get Unique Values from List
print(list(set([1,2,2,3,4,4])))
30. Count Frequency of List Elements
from collections import Counter; print(Counter([1,2,2,3,3,3])
31. Count Elements in List Within Range
print(sum(10 <= x <= 20 for x in [5,12,17,25]))
32. Check if List Contains Sublist
print([2,3] in [1,2,3,4])
33. Generate All Sublists
l = [1,2,3]; print([l[i:j] for i in range(len(l)) for j in range(i+1,len(l)+1)])
34. Sieve of Eratosthenes (Primes Up to n)
n = 30; p = [1]*n; p[0:2] = [0,0]
[print(i) for i in range(2,n) if p[i] and all(p[j]==0 or j%i for j in range(i*2,n,i))]
(Cleaner alt version for 34, slightly longer but clearer):
n = 30; p = [1]*n; p[:2] = [0,0]
for i in range(2, n):
if p[i]: p[i*2::i] = [0]*len(p[i*2::i])
print([i for i, val in enumerate(p) if val])
35. List with Range Concatenation
print([x+str(i) for i in range(1,6) for x in ['p','q']])
36. Get Variable ID
x = 42; print(id(x))
37. Common Items in Lists
print(set([1,2,3]) & set([2,3,4]))
38. Swap Every n-th and (n+1)th
l = [0,1,2,3,4,5]; l[::2],l[1::2] = l[1::2],l[::2]; print(l)
39. Convert Integers List to Single Integer
print(int(''.join(map(str, [11,33,50]))))
40. Split List by First Character
from collections import defaultdict; d=defaultdict(list)
[l := d[w[0]].append(w) for w in ['apple','ant','ball','bat']]
print(dict(d))
41. Create Multiple Lists
a,b,c = [],[],[]; print(a,b,c)
42. Find Missing & Additional Values
a,b = ['a','b','c'],['g','h','a']; print(set(a)-set(b), set(b)-set(a))
43. Split List into Variables
x,y,z = [1,2,3]; print(x,y,z)
44. Groups of Five Consecutive Numbers
print([list(range(i, i+5)) for i in range(1, 21, 5)])
45. Convert Pairs to Sorted Unique Array
print(sorted(set([1,2]+[2,3]+[3,4])))
46. Select Odd Items from List
print([x for x in [1,2,3,4,5,6] if x%2])
47. Insert Element Before Each List Item
print(['X' for _ in [1,2,3] for x in (0,1)][::2])
OR cleaner:
print(['X', *sum(([9,x] for x in [1,2,3]), [])][1:])
48. Print Nested Lists
[print(x) for x in [[1,2],[3,4],[5]]]
49. Convert List to List of Dicts
a,b=["Black","Red"],["#000","#F00"]
print([{'color_name': x, 'color_code': y} for x, y in zip(a,b)])
50. Sort Nested Dictionaries in List
l=[{'name':'A','score':5},{'name':'B','score':2}]
print(sorted(l, key=lambda x: x['score']))
51. Split List Every N-th Element
l = list('abcdefghijklm'); print([l[i::3] for i in range(3)])
52. Difference Between Two Lists
a,b=["red","green","blue"],["blue","black"]
print(set(a)-set(b), set(b)-set(a))
53. List with Infinite Elements (via Generator)
from itertools import count; inf = count(); print(next(inf), next(inf))
54. Concatenate List Elements
print(''.join(['a','b','c']))
55. Remove Key-Value from Dicts in List
l=[{'a':1,'b':2},{'a':3,'b':4}]; [d.pop('a') for d in l]; print(l)
56. String to List
print(list("hello"))
57. Check All Strings Match a Given String
print(all(x == "hi" for x in ["hi", "hi", "hi"]))
58. Replace Last Element with Another List
a=[1,2,3]; b=[4,5]; print(a[:-1]+b)
59. Check if N-th Element Exists in List
l=[1,2,3]; n=4; print(n < len(l))
60. Smallest Second Index Tuple
print(min([(1,3),(2,2),(3,5)], key=lambda x:x[1]))
61. Create List of Empty Dictionaries
print([{} for _ in range(5)])
62. Print Space-Separated List Elements
print(*[1, 2, 3, 4])
63. Insert String Before List Items
print(['emp'+str(i) for i in [1,2,3,4]])
64. Iterate Over Two Lists Simultaneously
for a, b in zip([1,2,3], ['a','b','c']): print(a, b)
65. Move Zeros to End of List
l = [3,0,4,0,6]; print([i for i in l if i]+[0]*l.count(0))
66. Find List with Highest Sum
print(max([[1,2],[3,4],[9,9]], key=sum))
67. Find Values Greater Than Specified Number
print([x for x in [1, 5, 8, 3] if x > 4])
68. Extend List Without Append
print([40,50,60]+[10,20,30])
69. Remove Duplicates from List of Lists
l = [[1,2],[3],[1,2]]; print([list(x) for x in set(tuple(i) for i in l)])
70. Find Items Starting with Specific Character
l = ['abc','bcd']; print([x for x in l if x.startswith('a')])
71. Check If All Dictionaries Are Empty
print(all(not d for d in [{},{},{}]))
72. Flatten Nested List Structure
from itertools import chain; print(list(chain.from_iterable(i if isinstance(i,list) else [i] for i in [1,
[2,3],4])))
73. Remove Consecutive Duplicates
from itertools import groupby; print([k for k, _ in groupby([1,1,2,2,3])])
74. Pack Consecutive Duplicates into Sublists
from itertools import groupby; print([list(g) for _, g in groupby([1,1,2,3,3])])
75. Run-Length Encoding
from itertools import groupby; print([[len(list(g)), k] for k, g in groupby([1,1,2,3,1])])
76. Modified Run-Length Encoding
from itertools import groupby
l = [1,1,2,3,4,4,5,1]
print([[len(list(g)), k] if len(list(g)) > 1 else k for k, g in groupby(l)])
77. Decode Run-Length Encoded List
l = [[2, 1], 2, 3, [2, 4], 5, 1]
print([i for x in l for i in ([x[1]]*x[0] if isinstance(x, list) else [x])])
78. Split List into Two Parts by Length
l, n = [1,1,2,3,4,4,5,1], 3
print((l[:n], l[n:]))
79. Remove K-th Element from List
l, k = [1,1,2,3,4,4,5,1], 2
l.pop(k); print(l)
80. Insert Element at Specified Position
l, k, e = [1,1,2,3,4,4,5,1], 2, 12
l.insert(k, e); print(l)
81. Extract Random Elements from List
import random
print(random.choices([1,1,2,3,4,4,5,1], k=3))
82. Generate Combinations from List
from itertools import combinations
print(list(combinations([1,2,3,4,5,6,7,8,9], 2)))
83. Round and Sum * Length
l = [22.4, 4.0, -16.22, -9.1, 11.0, -12.22, 14.2, -5.2, 17.5]
print(sum(round(x) for x in l) * len(l))
84. Round, Min/Max, Multiply by 5
l = [22.4, 4.0, 16.22, 9.1, 11.0, 12.22, 14.2, 5.2, 17.5]
r = sorted(set(round(x)*5 for x in l)); print(min(round(x) for x in l), max(round(x) for x in l));
print(*r)
85. Create Multidimensional List with Zeros
print([[0]*2 for _ in range(3)])
86. Create 3x3 Grid with Numbers
print([[1,2,3] for _ in range(3)])
87. Sum Matrix Columns from Console
r, c = int(input()), int(input())
m = [list(map(int, input().split())) for _ in range(r)]
print([sum(col) for col in zip(*m)])
88. Sum Primary Diagonal
n = int(input())
m = [list(map(int, input().split())) for _ in range(n)]
print(sum(m[i][i] for i in range(n)))
89. Zip Two Lists of Lists
a = [[1,3],[5,7],[9,11]]
b = [[2,4],[6,8],[10,12,14]]
print([x + y for x, y in zip(a, b)])
90. Count Lists in Nested List
l = [[1,3],[5,7],[9,11],[13,15,17]]
print(sum(isinstance(i, list) for i in l)
91. Find List with Max and Min Lengths
lst = [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]]
print(max(lst, key=len), min(lst, key=len))
92. Check if Nested List Is Subset
a = [[1, 3], [5, 7], [9, 11], [13, 15, 17]]
b = [[1, 3], [13, 15, 17]]
print(set(map(tuple, b)).issubset(map(tuple, a)))
93. Count Sublists Containing Element
lst = [[1, 3], [5, 7], [1, 11], [1, 15, 7]]
print(sum(1 for i in lst if 1 in i))
94. Count Unique Sublists in List
from collections import Counter
lst = [[1, 3], [5, 7], [1, 3], [13, 15, 17], [5, 7], [9, 11]]
print(dict(Counter(tuple(x) for x in lst)))
95. Sort Strings in Sublists
(Your example is ints but question says strings—we roll with the question)
lst = [['b', 'a'], ['c'], ['b', 'c', 'a']]
print([sorted(sub) for sub in lst])
96. Sort List of Lists by Length and Value
lst = [[2], [0], [1, 3], [0, 7], [9, 11], [13, 15, 17]]
print(sorted(lst, key=lambda x: (len(x), x)))
97. Remove Sublists Outside Range
lst = [[2], [0], [1, 2, 3], [0, 1, 2, 3, 6, 7], [9, 11], [13, 14, 15, 17]]
print([x for x in lst if all(10 <= i <= 20 for i in x)])
98. Scramble Letters in List Strings
import random
lst = ['Python', 'list', 'exercises', 'practice', 'solution']
print([''.join(random.sample(w, len(w))) for w in lst])
99. Find Max and Min in Heterogeneous List
lst = ['Python', 3, 2, 4, 5, 'version']
nums = [x for x in lst if isinstance(x, int)]
print(max(nums), min(nums))
100. Extract Common Index Elements from Lists
from itertools import zip_longest
lists = [[1, 1, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 7], [0, 1, 2, 3, 4, 5, 7]]
print([x[0] for x in zip(*lists) if all(i == x[0] for i in x)])
101. Sort Matrix by Row Sum
lst = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
print(sorted(lst, key=sum))
102. Extract Strings by Length
lst = ['Python', 'list', 'exercises', 'practice', 'solution']
print([x for x in lst if len(x) == 8])
103. Extract Continuous Elements from List
from itertools import groupby
lst = [1, 1, 3, 4, 4, 5, 6, 7]
n=2
print([k for k, g in groupby(lst) if len(list(g)) == n])
104. Difference Between Consecutive Numbers
lst = [1, 1, 3, 4, 4, 5, 6, 7]
print([b - a for a, b in zip(lst, lst[1:])])
105. Average of Two Lists
a = [1, 1, 3, 4, 4, 5, 6, 7]
b = [0, 1, 2, 3, 4, 4, 5, 7, 8]
print(sum(a + b) / (len(a) + len(b)))
106. Count Integers in Mixed List
lst = [1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]
print(sum(isinstance(i, int) for i in lst))
107. Remove Column from Nested List
lst = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
col = 0
print([row[:col] + row[col+1:] for row in lst])
108. Extract Column from Nested List
lst = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
col = 0
print([row[col] for row in lst])
109. Rotate List Left or Right
lst = [1,2,3,4,5,6,7,8,9,10]
k=2
print(lst[k:] + lst[:k]) # left
print(lst[-k:] + lst[:-k]) # right
110. Most Frequent Item in List
from collections import Counter
lst = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2]
print(Counter(lst).most_common(1)[0][0])
111. Access Multiple Elements by Index
lst = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2]
idx = [0,3,5,7,10]
print([lst[i] for i in idx])
112. Check If List Is Sorted
lst = [1,2,4,6,8,10,12,14,16,17]
print(lst == sorted(lst))
113. Remove Duplicate Dicts from List
lst = [{'Green':'#008000'},{'Black':'#000000'},{'Blue':'#0000FF'},{'Green':'#008000'}]
print([dict(t) for t in {tuple(d.items()) for d in lst}])
114. Extract N-th Element from Tuples
lst = [('Greyson Fulton',98,99),('Brady Kent',97,96),('Wyatt Knott',91,94),('Beau Turnbull',94,98)]
n=0
print([x[n] for x in lst])
115. Check for Unique Elements in List
lst = [1,2,4,6,8,2,1,4,10,12,14,12,16,17]
print(len(lst) == len(set(lst)))
116. Sort List of Lists by Index
lst = [('Greyson Fulton',98,99),('Brady Kent',97,96),('Wyatt Knott',91,94),('Beau Turnbull',94,98)]
idx = 2
print(sorted(lst, key=lambda x: x[idx]))
117. Remove Elements Present in Another List
l1 = [1,2,3,4,5,6,7,8,9,10]
l2 = [2,4,6,8]
print([x for x in l1 if x not in l2])
118. Difference Between Elements (n+1 - n)
lst = [2,4,6,8]
print([b - a for a, b in zip(lst, lst[1:])])
119. Check Substring in List of Strings
lst = ['red', 'black', 'white', 'green', 'orange']
sub = 'ack'
print(any(sub in s for s in lst))
120. Create List with Alternate Elements
lst = ['red','black','white','green','orange']
print(lst[::2])
121. Find Nested List Elements in Another List
lst1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
nested = [[12,18,23,25,45],[7,11,19,24,28],[1,5,8,18,15,16]]
print([list(set(i) & set(lst1)) for i in nested])
122. Find Common Elements in Nested Lists
from functools import reduce
lst = [[12,18,23,25,45],[7,12,18,24,28],[1,5,8,12,15,16,18]]
print(list(reduce(lambda x, y: set(x) & set(y), lst)))
123. Reverse Strings in List
lst = ['Red', 'Green', 'Blue', 'White', 'Black']
print([i[::-1] for i in lst])
124. Max and Min Product of Tuple Pairs
lst = [(2,7),(2,6),(1,8),(4,9)]
prods = [a*b for a,b in lst]
print((max(prods), min(prods)))
125. Product of Unique Numbers in List
from math import prod
lst = [10,20,30,40,20,50,60,40]
print(prod(set(lst)))
126. Interleave Multiple Lists
list1, list2, list3 = [1,2,3,4,5,6,7], [10,20,30,40,50,60,70], [100,200,300,400,500,600,700]
print([x for trio in zip(list1,list2,list3) for x in trio])
127. Remove Words Containing Specific Characters
lst = ['Red color','Orange#','Green','Orange @','White']
bad = ['#','color','@']
print([''.join([w for w in s.split() if all(c not in w for c in bad)]) for s in lst])
128. Sum Numbers in List Within Index Range
lst = [2,1,5,6,8,3,4,9,10,11,8,12]
print(sum(lst[8:11]))
129. Reverse Each List in Nested Lists
lst = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
print([x[::-1] for x in lst])
130. Count Same Pairs in Three Lists
a,b,c = [1,2,3,4,5,6,7,8],[2,2,3,1,2,6,7,9],[2,1,3,1,2,6,7,9]
print(sum(x==y==z for x,y,z in zip(a,b,c)))
131. Frequency of Consecutive Duplicates
lst = [1,2,2,2,4,4,4,5,5,5,5]
from itertools import groupby
g = [(k, len(list(v))) for k,v in groupby(lst)]
print(([k for k,_ in g], [v for _,v in g]))
132. Index of Max and Min Values in List
lst = [12,33,23,10,67,89,45,667,23,12,11,10,54]
max_i = [i for i,v in enumerate(lst) if v == max(lst)]
min_i = [i for i,v in enumerate(lst) if v == min(lst)]
print(max_i[0], ', '.join(map(str, min_i)))
133. Compare Common Elements in Lists for Order
def common_order(l1,l2): return [x for x in l1 if x in l2]
color1 = ['red','green','black','orange']
color2 = ['red','pink','green','white','black']
color3 = ['white','orange','pink','black']
print(common_order(color1,color2)==common_order(color2,color1))
print(common_order(color1,color3)==common_order(color3,color1))
print(common_order(color2,color3)==common_order(color3,color2))
134. Difference Between Two Lists with Duplicates
from collections import Counter
a = [1,1,2,3,3,4,4,5,6,7]
b = [1,1,2,4,5,6]
diff = (Counter(a)-Counter(b)).elements()
print(list(diff))
135. Iterate Consecutive Pairs in List
lst = [1,1,2,3,3,4,4,5]
print(list(zip(lst, lst[1:])))
Want the next batch too? I’m ready to keep this list train rolling! 🚂💻
Here are clean and minimal Python solutions for problems 136–150 — let’s knock these out like
a coding ninja ⚔️:
136. Remove Duplicate Words from List
lst = ['Python', 'Exercises', 'Practice', 'Solution', 'Exercises']
res = list(dict.fromkeys(lst))
print(res)
137. Find First Even and Odd Numbers
lst = [1, 3, 5, 7, 4, 1, 6, 8]
even = next(x for x in lst if x % 2 == 0)
odd = next(x for x in lst if x % 2)
print((even, odd))
138. Sort Mixed List (Numbers Before Strings)
lst = [19, 'red', 12, 'green', 'blue', 10, 'white', 'green', 1]
res = sorted([x for x in lst if isinstance(x, int)]) + sorted([x for x in lst if isinstance(x, str)])
print(res)
139. Sort List of String Numbers Numerically
lst = ['4', '12', '45', '7', '0', '100', '200', '-12', '-500']
res = sorted(map(int, lst))
print(res)
140. Remove Item from List of Lists
lst = [['Red', 'Maroon', 'Yellow', 'Olive'],
['#FF0000', '#800000', '#FFFF00', '#808000'],
['rgb(255,0,0)', 'rgb(128,0,0)', 'rgb(255,255,0)', 'rgb(128,128,0)']]
res1 = [i[1:] for i in lst]
res2 = [i[:1]+i[2:] for i in lst]
res3 = [i[:-1] for i in lst]
print(res1)
print(res2)
print(res3)
141. Remove Empty Lists from Nested List
lst = [[], [], [], 'Red', 'Green', [1, 2], 'Blue', [], []]
res = [x for x in lst if x != []]
print(res)
142. Sum of Specific Column in List of Lists
lst = [[1, 2, 3, 2], [4, 5, 6, 2], [7, 8, 9, 5]]
print(sum(row[0] for row in lst))
print(sum(row[1] for row in lst))
print(sum(row[3] for row in lst))
143. Frequency of Elements in Nested Lists
from collections import Counter
lst = [[1, 2, 3, 2], [4, 5, 6, 2], [7, 8, 9, 5]]
flat = [i for sub in lst for i in sub]
print(dict(Counter(flat)))
144. Extract Specified Element from 2D List
lst = [[1, 2, 3, 2], [4, 5, 6, 2], [7, 1, 9, 5]]
print([row[0] for row in lst])
print([row[2] for row in lst])
145. Generate Number in Range Except Specific
import random
def gen_exclude(start, end, exclude):
valid = [x for x in range(start, end+1) if x not in exclude]
return random.choice(valid)
print(gen_exclude(1, 10, [2, 9, 10]))
print(gen_exclude(-5, 5, [-5, 0, 4, 3, 2]))
146. Sum of Digits in List Numbers
lst = [10, 20, 4, 5, 'b', 70, 'a']
res = sum(sum(int(d) for d in str(abs(x))) for x in lst if isinstance(x, int))
print(res)
147. Randomly Interleave Two Lists
import random
l1 = [1, 2, 7, 8, 3, 7]
l2 = [4, 3, 8, 9, 4, 3, 8, 9]
combined = l1 + l2
random.shuffle(combined)
print(combined)
148. Remove Specific Words from List
lst = ['red', 'green', 'blue', 'white', 'black', 'orange']
remove = ['white', 'orange']
res = [x for x in lst if x not in remove]
print(res)
149. Generate All Combinations of List Elements
from itertools import combinations
lst = ['orange', 'red', 'green', 'blue']
res = []
for r in range(len(lst)+1):
for combo in combinations(lst, r):
res.append(list(combo))
print(res)
150. Reverse List of Lists
lst = [['orange', 'red'], ['green', 'blue'], ['white', 'black', 'pink']]
print(lst[::-1])
lst2 = [[1, 2, 3, 4], [0, 2, 4, 5], [2, 3, 4, 2, 4]]
print(lst2[::-1])
Here’s your quick, minimalist Python code for each of the questions from 151 to 160. All solutions
are kept short, clean, and straight to the point — just like a pro coder on a coffee rush ☕🚀
151. Max and Min in Index Range
lst = [4,3,0,5,3,0,2,3,4,2,4,3,5]
print(max(lst[3:9]), min(lst[3:9]))
152. Merge Sorted Lists with Heapq
import heapq
print(list(heapq.merge([1,3,5,7,9,11], [0,2,4,6,8,10])))
153. Check Element Frequency in List
lst = [0,1,3,5,0,3,4,5,0,8,0,3,6,0,3,1,1,0]
print(lst.count(3) >= 4, lst.count(0) >= 5, lst.count(8) >= 3)
154. Join Two Lists of Lists Element-Wise
a = [[10,20],[30,40],[50,60],[30,20,80]]
b = [[61],[12,14,15],[12,13,19,20],[12]]
print([x + y for x, y in zip(a, b)])
155. Add Lists from Left
a, b = [2,4,7,0,5,8], [3,3,-1,7]
print([x+y for x,y in zip(a,b)] + a[len(b):])
156. Add Lists from Right
a, b = [2,4,7,0,5,8], [3,3,-1,7]
d = len(a) - len(b)
print(a[:d] + [x+y for x,y in zip(a[d:], b)])
157. Interleave Lists of Varying Lengths
from itertools import zip_longest
a = [[2,4,7,0,5,8], [2,5,8], [0,1], [3,3,-1,7]]
print([x for t in zip_longest(*a) for x in t if x is not None])
158. Max and Min in List of Tuples
lst = [('V',60),('VI',70),('VII',75),('VIII',72),('IX',78),('X',70)]
vals = [x[1] for x in lst]
print(max(vals), min(vals))
159. Append Value Multiple Times
print(['7']*5)
print([1,2,3,4]+[5]*6)
print([[1,2,5]]*4)
print([[5,6,7]] + [[1,2,5]]*3)
160. Remove Elements by Condition
lst = [3,10,4,7,5,7,8,3,3,4,5,9,3,4,9,8,5]
n, c = 4, 0
print([x for x in lst if not (x%2==0 and (c:=c+1)<=n)])
# 161. Check Strictly Increasing List
def is_strictly_increasing(lst):
return all(x < y for x, y in zip(lst, lst[1:])) or \
any(all(x < y for x, y in zip(lst[:i] + lst[i+1:], lst[1:i] + lst[i+2:])) for i in range(len(lst)))
print(is_strictly_increasing([1, 2, 3, 4, 5])) # True
print(is_strictly_increasing([1, 3, 2, 4, 5])) # True
# 162. Find Last Occurrence of Item
lst = ['s', 'd', 'f', 's', 'd', 'f', 's', 'f', 'k', 'o', 'p', 'i', 'w', 'e', 'k', 'c']
print([lst[::-1].index(x) for x in ['f', 'c', 'k', 'w']])
# 163. Index of First Element Greater Than X
lst = [12, 45, 23, 67, 78, 90, 100, 76, 38, 62, 73, 29, 83]
print([next((i for i, v in enumerate(lst) if v > x), -1) for x in [73, 21, 80, 55]])
# 164. Filter List by Conditions
lst = [12, 45, 23, 67, 78, 90, 45, 32, 100, 76, 38, 62, 73, 29, 83]
print(len([x for x in lst if x % 2 == 0 and x > 45]))
# 165. Split List into Chunks
def split_list(lst, size):
return [lst[i:i + size] for i in range(0, len(lst), size)]
lst = [12, 45, 23, 67, 78, 90, 45, 32, 100, 76, 38, 62, 73, 29, 83]
print(split_list(lst, 3))
print(split_list(lst, 4))
print(split_list(lst, 5))
# 166. Remove None from List
lst = [12, 0, None, 23, None, -55, 234, 89, None, 0, 6, -12]
print([x for x in lst if x is not None])
# 167. Convert Strings to Lists of Characters
lst = ['Red', 'Maroon', 'Yellow', 'Olive']
print([list(x) for x in lst])
# 168. Display List Vertically
lst = ['a', 'b', 'c', 'd', 'e', 'f']
print("\n".join(lst))
lst = [[1, 2, 5], [4, 5, 8], [7, 3, 6]]
for row in zip(*lst):
print(" ".join(map(str, row)))
# 169. Convert Strings to List of Characters
lst = ['red', 'white', 'a', 'b', 'black', 'f']
print(list("".join(lst)))
# 170. Insert Element After Nth Position
def insert_after(lst, n, elem):
return [lst[i] if (i + 1) % (n + 1) != 0 else [lst[i], elem] for i in range(len(lst))]
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print([item for sublist in insert_after(lst, 2, 'a') for item in (sublist if isinstance(sublist, list) else
[sublist])])
print([item for sublist in insert_after(lst, 4, 'b') for item in (sublist if isinstance(sublist, list) else
[sublist])])
# 171. Concatenate Lists Element-Wise
lst1 = ['0', '1', '2', '3', '4']
lst2 = ['red', 'green', 'black', 'blue', 'white']
lst3 = ['100', '200', '300', '400', '500']
print([f"{a}{b}{c}" for a, b, c in zip(lst1, lst2, lst3)])
# 172. Remove Last N Elements from List
lst = [2, 3, 9, 8, 2, 0, 39, 84, 2, 2, 34, 2, 34, 5, 3, 5]
n=3
print(lst[:-n])
n=5
print(lst[:-n])
n=1
print(lst[:-n])
# 173. Merge List Items by Index Range
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(lst[:2] + ['cd'] + lst[4:])
print(lst[:3] + ['defg'])
# 174. Add Number to Each Element in List
lst = [3, 8, 9, 4, 5, 0, 5, 0, 3]
print([x + 3 for x in lst])
lst = [3.2, 8, 9.9, 4.2, 5, 0.1, 5, 3.11, 0]
print([x + 0.51 for x in lst])
# 175. Min and Max of Tuple Positions
lst = [(2, 3), (2, 4), (0, 6), (7, 1)]
print([max(x[i] for x in lst) for i in range(2)])
print([min(x[i] for x in lst) for i in range(2)])
Here’s a simple, minimal-line solution for each question from 176 to 200. Let's zoom through
them like it's a speedrun 🏁🔥:
176. Divide Elements of Two Lists
a = [7, 2, 3, 4, 9, 2, 3]; b = [9, 8, 2, 3, 3, 1, 2]
print([i/j for i, j in zip(a, b)])
177. Common Elements in List of Lists
from functools import reduce
print(list(reduce(set.intersection, map(set, [[7,2,3],[9,2,3],[8,2,3]]))))
178. Insert Element After Every Nth Position
a, n, x = [1,2,3,4,5,6], 2, 99
print([e for i, v in enumerate(a) for e in ([v, x] if (i+1)%n==0 else [v])])
179. Create Largest Number from List
from functools import cmp_to_key
nums = [3, 40, 41, 43, 74, 9]
cmp = lambda a,b: -1 if str(a)+str(b) > str(b)+str(a) else 1
print(''.join(map(str, sorted(nums, key=cmp_to_key(cmp)))))
180. Create Smallest Number from List
cmp = lambda a,b: -1 if str(a)+str(b) < str(b)+str(a) else 1
print(''.join(map(str, sorted(nums, key=cmp_to_key(cmp)))))
181. Iterate List Cyclically at Index
a, i = ['a','b','c','d'], 2
print(a[i:] + a[:i])
182. Max and Min Sublist Sums
a = [[1,2],[3,4],[0,0]]
print(max(a, key=sum), min(a, key=sum))
183. Unique Values in List of Lists
a = [[1,2],[2,3],[4]]
print(sorted(set(i for sub in a for i in sub)))
184. Generate Bigrams from List of Strings
a = ['a b c','d e f']
print([(w[i], w[i+1]) for s in a for w in [s.split()] for i in range(len(w)-1)])
185. Convert Decimal to Binary List
n = 45
print([int(b) for b in bin(n)[2:]])
186. Swap Sublists in List
a = list(range(16))
a[1:6], a[6:9] = a[6:9], a[1:6]
print(a)
187. Convert Tuples to Strings
a = [('a','b'), ('c','d')]
print([' '.join(t) for t in a])
188. Sort Tuples by Specified Element
a = [('a',2,3),('b',1,5)]
print(sorted(a, key=lambda x: x[0])) # Change index for other elements
189. Swap First and Last Element
a = [1,2,3]
a[0], a[-1] = a[-1], a[0]
print(a)
190. Largest Products from Two Lists
a,b,n = [1,2],[3,4], 2
print(sorted((x*y for x in a for y in b), reverse=True)[:n])
191. Max and Min of Three Lists
a = [1,9]; b = [3,4]; c = [0,8]
print(max(max(a),max(b),max(c)), min(min(a),min(b),min(c)))
192. Remove Strings from List of Tuples
a = [(1,'a'),(2,'b',3)]
print([tuple(i for i in t if not isinstance(i,str)) for t in a])
193. Matrix Dimensions
a = [[1,2],[3,4]]
print((len(a), len(a[0]) if a else 0))
194. Sum Lists with Different Lengths
from itertools import zip_longest
a = [[1,2],[2,3,4]]
print([sum(i for i in t if i) for t in zip_longest(*a)])
195. Reverse List with Original Index
a = ['a','b','c']
for i, v in reversed(list(enumerate(a))): print(i, v)
196. Move Element to End of List
a = ['a','b','c']; e = 'b'
a.remove(e); a.append(e)
print(a)
197. Average N-th Element in Nested Lists
a = [[0,1],[2,3,4]]
print([sum(x)/len(x) for x in zip(*[l+[None]*(max(map(len,a))-len(l)) for l in a]) if None not in x])
198. Indices of Common Elements in Lists
a,b = [1,2,3,4,5], [5,6]
print([i for i,v in enumerate(a) if v in b])
199. Convert Unicode List to Strings
a = ['S001', 'S002']
print([str(i) for i in a])
200. Pair Consecutive Elements in List
a = [1,2,3,4]
print(list(zip(a, a[1:])))
Want me to save these into a file or turn ‘em into a notebook too? Or should I keep ‘em coming
like TikToks on your FYP? 😄