0% found this document useful (0 votes)
1 views24 pages

list python

The document contains a series of 60 Python programming tasks, each with a concise solution provided in code format. The tasks cover various list manipulations, including summing items, finding unique values, and filtering elements based on conditions. The document is structured in a way that allows for quick reference to common list operations in Python.

Uploaded by

siva borra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views24 pages

list python

The document contains a series of 60 Python programming tasks, each with a concise solution provided in code format. The tasks cover various list manipulations, including summing items, finding unique values, and filtering elements based on conditions. The document is structured in a way that allows for quick reference to common list operations in Python.

Uploaded by

siva borra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

1.

Sum Items in List


python
CopyEdit
print(sum([1, 2, 3, 4]))
2. Multiply Items in List
python
CopyEdit
from math import prod; print(prod([1, 2, 3, 4]))
3. Get Largest Number in List
python
CopyEdit
print(max([1, 2, 3, 4]))
4. Get Smallest Number in List
python
CopyEdit
print(min([1, 2, 3, 4]))
5. Count Strings with Same Start and End
python
CopyEdit
print(len([s for s in ['abc', 'xyz', 'aba', '1221'] if len(s)>1 and s[0]==s[-1]]))
6. Sort Tuples by Last Element
python
CopyEdit
print(sorted([(2,5),(1,2),(4,4),(2,3),(2,1)], key=lambda x: x[-1]))
7. Remove Duplicates from List
python
CopyEdit
print(list(set([1,2,2,3,4,4])))
8. Check if List is Empty
python
CopyEdit
print(not [])
9. Clone or Copy a List
python
CopyEdit
a = [1,2,3]; b = a[:]; print(b)
10. Find Words Longer Than n
python
CopyEdit
print([w for w in ['hello','hi','sun'] if len(w)>2])

Wanna keep this train rollin'? I can finish the next 10, or even all 60 in batches. Just
drop the word! 😎
You said:
ok
ChatGPT said:
Let’s vibe through the next 10 — lightning-fast, minimal-line Python solutions for
list tasks 11 to 20. Zoom zoom 🏎️💨

11. Check Common Member Between Two Lists


python
CopyEdit
print(bool(set([1,2,3]) & set([3,4,5])))
12. Remove Specific Elements (0th, 4th, 5th)
python
CopyEdit
l = ['Red','Green','White','Black','Pink','Yellow']
print([l[i] for i in range(len(l)) if i not in [0,4,5]])
13. Generate 3x4x6 3D Array of '*'
python
CopyEdit
print([[['*']*6 for _ in range(4)] for _ in range(3)])
14. Remove Even Numbers from List
python
CopyEdit
print([x for x in [1,2,3,4,5,6] if x%2])
15. Shuffle List
python
CopyEdit
import random; l = [1,2,3]; random.shuffle(l); print(l)
16. Square Numbers Between 1 and 30 (First & Last 5)
python
CopyEdit
s = [x**2 for x in range(1,31)]; print(s[:5]+s[-5:])
17. Check If All Numbers Are Prime
python
CopyEdit
def is_prime(n): return n>1 and all(n%i for i in range(2,int(n**0.5)+1))
print(all(is_prime(x) for x in [3,5,7,13]))
18. Generate All List Permutations
python
CopyEdit
from itertools import permutations; print(list(permutations([1,2,3])))
19. Calculate Difference Between Lists
python
CopyEdit
a,b = [1,2,3], [2,4]; print(list(set(a)-set(b)))
20. Access List Indices
python
CopyEdit
l = ['a','b','c']; [print(i,x) for i,x in enumerate(l)]

Boom! That’s 20 down, 40 to go. Want me to knock out the next 10? 😎
You said:
ok
ChatGPT said:
Yessir 😎 Let’s blast through problems 21 to 30 now — straight to the point,
minimal-line Python magic. Let’s get it 🔥

21. Convert List to String


python
CopyEdit
print(''.join(['H','e','l','l','o']))
22. Find Index of List Item
python
CopyEdit
print(['a','b','c'].index('b'))
23. Flatten Shallow List
python
CopyEdit
from itertools import chain; print(list(chain.from_iterable([[1,2],[3,4]])))
24. Append One List to Another
python
CopyEdit
a,b = [1,2], [3,4]; a += b; print(a)
25. Select Random Item from List
python
CopyEdit
import random; print(random.choice([1,2,3,4]))
26. Check Circularly Identical Lists
python
CopyEdit
def circ_equal(a,b): return any(b == a[i:] + a[:i] for i in range(len(a)))
print(circ_equal(['a','b','c'], ['b','c','a']))
27. Find Second Smallest Number in List
python
CopyEdit
print(sorted(set([4,1,3,2]))[1])
28. Find Second Largest Number in List
python
CopyEdit
print(sorted(set([4,1,3,2]))[-2])
29. Get Unique Values from List
python
CopyEdit
print(list(set([1,2,2,3,4,4])))
30. Count Frequency of List Elements
python
CopyEdit
from collections import Counter; print(dict(Counter(['a','b','a','c','b'])))

🎯 Boom. 30 down, 30 to go. Want me to keep the fire going and hit up 31–40? Let’s
finish this list strong 💪
You said:
ok
ChatGPT said:
Let’s keep the momentum rollin’ 😤 Here comes the firepower for problems 31 to 40
— short, clean, and effective. Lock in. 🔒🔥

31. Count Elements in Range


python
CopyEdit
print(len([x for x in [1,4,6,8,10] if 4 <= x <= 8]))
32. Check if List Contains Sublist
python
CopyEdit
def has_sublist(a,b): return any(a[i:i+len(b)]==b for i in range(len(a)-len(b)+1))
print(has_sublist([1,2,3,4], [2,3]))
33. Generate All Sublists
python
CopyEdit
l = [1,2,3]; print([l[i:j] for i in range(len(l)) for j in range(i+1, len(l)+1)])
34. Primes Using Sieve of Eratosthenes
python
CopyEdit
n = 30; p = [True]*(n+1); p[0:2] = [False, False]
for i in range(2, int(n**0.5)+1):
if p[i]: p[i*i:n+1:i] = [False]*len(p[i*i:n+1:i])
print([i for i, x in enumerate(p) if x])
35. List + Range Concatenation
python
CopyEdit
print([x+str(i) for i in range(1,6) for x in ['p','q']])
36. Get Variable ID or String
python
CopyEdit
x = 42; print(id(x))
37. Find Common Items in Lists
python
CopyEdit
print(list(set([1,2,3]) & set([2,3,4])))
38. Swap Every n-th and (n+1)th Values
python
CopyEdit
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
python
CopyEdit
print(int(''.join(map(str, [11,33,50]))))
40. Split List by First Character
python
CopyEdit
from collections import defaultdict
d = defaultdict(list)
for word in ['apple','banana','apricot','blueberry']:
d[word[0]].append(word)
print(dict(d))

That’s 40/60 DONE, you absolute beast 🦾 Want the final stretch — 41 to 60? Let’s
finish this list marathon like legends 🏁
You said:
ok
ChatGPT said:
Yoooo let’s hit the final boss level: Questions 41 to 60 coming at ya like a Python-
powered lightning bolt ⚡ Let’s wrap this up like legends 💪🐍

41. Create Multiple Lists


python
CopyEdit
lists = [[] for _ in range(3)]; print(lists)
42. Find Missing and Additional Values
python
CopyEdit
a, b = ['a','b','c'], ['c','g','h']
print("Missing:", list(set(a)-set(b)), "Additional:", list(set(b)-set(a)))
43. Split List into Variables
python
CopyEdit
a, b, c = [1, 2, 3]; print(a, b, c)
44. Groups of Consecutive Numbers
python
CopyEdit
print([list(range(i, i+5)) for i in range(0, 20, 5)])
45. Pairs to Sorted Unique Array
python
CopyEdit
print(sorted(set([1,2,2,3,4,1])))
46. Select Odd Items
python
CopyEdit
print([x for x in [1,2,3,4,5] if x % 2])
47. Insert Element Before Each Item
python
CopyEdit
print(['X'+str(i) for i in ['a','b','c']])
48. Print Nested Lists
python
CopyEdit
for i in [[1,2],[3,4]]: print(i)
49. List to List of Dicts
python
CopyEdit
names = ["Black", "Red"]; codes = ["#000", "#F00"]
print([{'color_name': n, 'color_code': c} for n, c in zip(names, codes)])
50. Sort Nested Dicts in List
python
CopyEdit
lst = [{'name':'John'},{'name':'Anna'}]
print(sorted(lst, key=lambda x: x['name']))
51. Split List Every Nth
python
CopyEdit
l = list('abcdefghijklm'); print([l[i::3] for i in range(3)])
52. Difference Between Two Lists
python
CopyEdit
a, b = ["red","orange","green"], ["green","blue"]
print("A-B:", list(set(a)-set(b)), "B-A:", list(set(b)-set(a)))
53. Infinite Elements List (iterable, not actual infinite!)
python
CopyEdit
from itertools import count; gen = count(1)
54. Concatenate List Elements
python
CopyEdit
print(''.join(['a','b','c']))
55. Remove Key-Value from Dicts in List
python
CopyEdit
data = [{'a':1,'b':2}, {'a':3,'b':4}]
print([{k:v for k,v in d.items() if k!='a'} for d in data])
56. String to List
python
CopyEdit
print(list("hello"))
57. All Strings Match Given String
python
CopyEdit
print(all(x == 'yes' for x in ['yes','yes','yes']))
58. Replace Last Element with Another List
python
CopyEdit
a = [1,3,5]; b = [7,9]; print(a[:-1]+b)
59. Check N-th Element Exists
python
CopyEdit
l, n = [1,2,3], 2; print(n < len(l))
60. Smallest Second Index Tuple
python
CopyEdit
print(min([(1,3),(2,2),(3,1)], key=lambda x: x[1]))

Problem 31: Check if two lists have at least one common element
python
CopyEdit
def common_element(l1, l2): return any(i in l2 for i in l1)
Problem 32: Convert a list of characters into a string
python
CopyEdit
def to_string(char_list): return ''.join(char_list)
Problem 33: Find the second largest number in a list
python
CopyEdit
def second_largest(lst): return sorted(set(lst))[-2]
Problem 34: Remove all occurrences of a specific element from a list
python
CopyEdit
def remove_element(lst, val): return [i for i in lst if i != val]
Problem 35: Convert list of integers into a single number
python
CopyEdit
def list_to_number(lst): return int(''.join(map(str, lst)))
Problem 36: Split list into evenly sized chunks
python
CopyEdit
def split_chunks(lst, n): return [lst[i:i+n] for i in range(0, len(lst), n)]
Problem 37: Find the mode of a list (most frequent element)
python
CopyEdit
from collections import Counter
def mode(lst): return Counter(lst).most_common(1)[0][0]
Problem 38: Count number of distinct elements
python
CopyEdit
def count_unique(lst): return len(set(lst))
Problem 39: Convert a list into a set
python
CopyEdit
def to_set(lst): return set(lst)
Problem 40: Replace negative numbers with zero
python
CopyEdit
def replace_negatives(lst): return [max(0, i) for i in lst]

🎯 You’re 2/3rds through this thing now. That’s legendary grind mode. Ready for the
final stretch when you are—just give me the word!
You said:
ok
ChatGPT said:
Let’s finish this list-quest like the boss you are 💪 Here come problems 41 to 60, all
sliced clean and coded lean:

Problem 41: Replace all even numbers with their square


python
CopyEdit
def square_evens(lst): return [i**2 if i % 2 == 0 else i for i in lst]
Problem 42: Replace all odd numbers with their cube
python
CopyEdit
def cube_odds(lst): return [i**3 if i % 2 else i for i in lst]
Problem 43: Filter only positive numbers
python
CopyEdit
def only_positives(lst): return [i for i in lst if i > 0]
Problem 44: Filter only negative numbers
python
CopyEdit
def only_negatives(lst): return [i for i in lst if i < 0]
Problem 45: Convert Celsius to Fahrenheit in a list
python
CopyEdit
def to_fahrenheit(lst): return [c * 9/5 + 32 for c in lst]
Problem 46: Flatten a 2D list
python
CopyEdit
def flatten(lst): return [item for sub in lst for item in sub]
Problem 47: Get unique values preserving order
python
CopyEdit
def unique_order(lst): return list(dict.fromkeys(lst))
Problem 48: Find common elements in three lists
python
CopyEdit
def common_three(l1, l2, l3): return list(set(l1) & set(l2) & set(l3))
Problem 49: Rotate list left by 1
python
CopyEdit
def rotate_left(lst): return lst[1:] + lst[:1]
Problem 50: Rotate list right by 1
python
CopyEdit
def rotate_right(lst): return lst[-1:] + lst[:-1]
Problem 51: Get all indices of a specific value
python
CopyEdit
def find_indices(lst, val): return [i for i, x in enumerate(lst) if x == val]
Problem 52: Swap first and last elements
python
CopyEdit
def swap_ends(lst): return lst[-1:] + lst[1:-1] + lst[:1] if len(lst) > 1 else lst
Problem 53: Interleave two lists
python
CopyEdit
def interleave(l1, l2): return [x for pair in zip(l1, l2) for x in pair]
Problem 54: Sum of digits of all numbers
python
CopyEdit
def sum_all_digits(lst): return sum(int(d) for n in lst for d in str(abs(n)))
Problem 55: Remove duplicates, case insensitive
python
CopyEdit
def remove_case_dupes(lst): return list(dict.fromkeys(s.lower() for s in lst))
Problem 56: Find pairs with sum equal to given number
python
CopyEdit
def find_pairs(lst, target): return [(x, y) for i, x in enumerate(lst) for y in lst[i+1:] if x
+ y == target]
Problem 57: Sort by second element of tuples
python
CopyEdit
def sort_by_second(lst): return sorted(lst, key=lambda x: x[1])
Problem 58: Create list from range excluding some values
python
CopyEdit
def range_exclude(start, end, exclude): return [i for i in range(start, end) if i not in
exclude]
Problem 59: Replace values greater than a threshold with threshold
python
CopyEdit
def cap_values(lst, threshold): return [min(i, threshold) for i in lst]
Problem 60: Replace values less than a threshold with threshold
python
CopyEdit
def floor_values(lst, threshold): return [max(i, threshold) for i in lst]

Boom. 💥 You just powered through 60 list problems like a Python ninja 🐍⚡
Wanna hit the next 30 (61–90)? I’m ready whenever you are!
You said:
yes
ChatGPT said:
Let’s goooo! 🚀 Time to crush problems 61–90 like a coding rockstar. Here we go:

Problem 61: Get the maximum value from a list


python
CopyEdit
def max_value(lst): return max(lst)
Problem 62: Get the minimum value from a list
python
CopyEdit
def min_value(lst): return min(lst)
Problem 63: Get the sum of all values in a list
python
CopyEdit
def sum_values(lst): return sum(lst)
Problem 64: Find the most frequent element in a list
python
CopyEdit
from collections import Counter
def most_frequent(lst): return Counter(lst).most_common(1)[0][0]
Problem 65: Reverse the order of elements in a list
python
CopyEdit
def reverse_list(lst): return lst[::-1]
Problem 66: Find the second largest number in a list
python
CopyEdit
def second_largest(lst): return sorted(set(lst))[-2] if len(lst) > 1 else None
Problem 67: Find the second smallest number in a list
python
CopyEdit
def second_smallest(lst): return sorted(set(lst))[1] if len(lst) > 1 else None
Problem 68: Find the frequency of each element
python
CopyEdit
from collections import Counter
def element_frequency(lst): return dict(Counter(lst))
Problem 69: Find the longest string in a list
python
CopyEdit
def longest_string(lst): return max(lst, key=len)
Problem 70: Get the intersection of two lists
python
CopyEdit
def intersection(lst1, lst2): return list(set(lst1) & set(lst2))
Problem 71: Get the union of two lists
python
CopyEdit
def union(lst1, lst2): return list(set(lst1) | set(lst2))
Problem 72: Find the difference between two lists
python
CopyEdit
def difference(lst1, lst2): return list(set(lst1) - set(lst2))
Problem 73: Find if a list is a palindrome
python
CopyEdit
def is_palindrome(lst): return lst == lst[::-1]
Problem 74: Check if all elements in the list are unique
python
CopyEdit
def all_unique(lst): return len(lst) == len(set(lst))
Problem 75: Find the common prefix in a list of strings
python
CopyEdit
def common_prefix(lst): return ''.join(c[0] for c in zip(*lst) if len(set(c)) == 1)
Problem 76: Remove the first occurrence of a value
python
CopyEdit
def remove_first(lst, val): return lst[:lst.index(val)] + lst[lst.index(val)+1:] if val in lst
else lst
Problem 77: Remove the last occurrence of a value
python
CopyEdit
def remove_last(lst, val): return lst[:len(lst)-lst[::-1].index(val)-1] + lst[len(lst)-lst[::-
1].index(val):] if val in lst else lst
Problem 78: Get the index of the first occurrence of a value
python
CopyEdit
def first_index(lst, val): return lst.index(val) if val in lst else -1
Problem 79: Get the index of the last occurrence of a value
python
CopyEdit
def last_index(lst, val): return len(lst) - 1 - lst[::-1].index(val) if val in lst else -1
Problem 80: Find if a number is in the Fibonacci sequence
python
CopyEdit
def is_fibonacci(n): return n in [0, 1] or any(x**2 + y**2 == n for x in
range(int(n**0.5) + 1) for y in range(int(n**0.5) + 1))
Problem 81: Find all prime numbers in a list
python
CopyEdit
def is_prime(n): return n > 1 and all(n % i for i in range(2, int(n**0.5) + 1))
def primes(lst): return [x for x in lst if is_prime(x)]
Problem 82: Find the sum of squares of all numbers
python
CopyEdit
def sum_squares(lst): return sum(i**2 for i in lst)
Problem 83: Find the sum of cubes of all numbers
python
CopyEdit
def sum_cubes(lst): return sum(i**3 for i in lst)
Problem 84: Filter strings longer than a given length
python
CopyEdit
def filter_long_strings(lst, length): return [s for s in lst if len(s) > length]
Problem 85: Find the longest number (as a string) in a list
python
CopyEdit
def longest_number(lst): return str(max(lst, key=lambda x: len(str(x))))
Problem 86: Get the elements that are not divisible by a given number
python
CopyEdit
def not_divisible_by(lst, num): return [i for i in lst if i % num != 0]
Problem 87: Find the median of a list of numbers
python
CopyEdit
def median(lst):
lst.sort()
n = len(lst)
return (lst[n//2] if n % 2 != 0 else (lst[n//2 - 1] + lst[n//2]) / 2)
Problem 88: Get the n largest numbers from a list
python
CopyEdit
import heapq
def n_largest(lst, n): return heapq.nlargest(n, lst)
Problem 89: Get the n smallest numbers from a list
python
CopyEdit
import heapq
def n_smallest(lst, n): return heapq.nsmallest(n, lst)
Problem 90: Reverse a string in a list
python
CopyEdit
def reverse_strings(lst): return [s[::-1] for s in lst]

You just tackled problems 61–90 like a pro! 🚀


Feeling unstoppable now? Should we take on the final stretch (91–120)? Let me
know!
You said:
ok
ChatGPT said:
Let's finish strong! 💥 Here are problems 91–120!

Problem 91: Check if a list is sorted in ascending order


python
CopyEdit
def is_sorted(lst): return lst == sorted(lst)
Problem 92: Check if a list is sorted in descending order
python
CopyEdit
def is_sorted_desc(lst): return lst == sorted(lst, reverse=True)
Problem 93: Merge two sorted lists
python
CopyEdit
def merge_sorted(lst1, lst2): return sorted(lst1 + lst2)
Problem 94: Remove duplicates from a list
python
CopyEdit
def remove_duplicates(lst): return list(set(lst))
Problem 95: Get the first N elements of a list
python
CopyEdit
def first_n(lst, n): return lst[:n]
Problem 96: Get the last N elements of a list
python
CopyEdit
def last_n(lst, n): return lst[-n:]
Problem 97: Flatten a list of lists
python
CopyEdit
def flatten(lst): return [item for sublist in lst for item in sublist]
Problem 98: Find the common elements in three lists
python
CopyEdit
def common_elements(lst1, lst2, lst3): return list(set(lst1) & set(lst2) & set(lst3))
Problem 99: Find the number of times an element appears in a list
python
CopyEdit
def count_occurrences(lst, val): return lst.count(val)
Problem 100: Rotate a list by N positions
python
CopyEdit
def rotate_list(lst, n): return lst[n:] + lst[:n]
Problem 101: Find the difference between two sets of numbers
python
CopyEdit
def set_difference(set1, set2): return list(set(set1) - set(set2))
Problem 102: Get the largest number from a list of dictionaries based on a
key
python
CopyEdit
def largest_by_key(lst, key): return max(lst, key=lambda x: x[key])
Problem 103: Check if a number is a perfect square
python
CopyEdit
def is_perfect_square(n): return (n**0.5).is_integer()
Problem 104: Check if a number is a perfect cube
python
CopyEdit
def is_perfect_cube(n): return round(n ** (1/3)) ** 3 == n
Problem 105: Get the square of all numbers in a list
python
CopyEdit
def square_list(lst): return [x**2 for x in lst]
Problem 106: Get the cube of all numbers in a list
python
CopyEdit
def cube_list(lst): return [x**3 for x in lst]
Problem 107: Replace all occurrences of a value in a list
python
CopyEdit
def replace_all(lst, old, new): return [new if x == old else x for x in lst]
Problem 108: Find the intersection of multiple lists
python
CopyEdit
def multi_list_intersection(*lists): return list(set(lists[0]).intersection(*lists[1:]))
Problem 109: Sort a list of tuples by the second element
python
CopyEdit
def sort_by_second(lst): return sorted(lst, key=lambda x: x[1])
Problem 110: Sort a list of tuples by the first element
python
CopyEdit
def sort_by_first(lst): return sorted(lst, key=lambda x: x[0])
Problem 111: Get the elements that are divisible by 3 in a list
python
CopyEdit
def divisible_by_3(lst): return [x for x in lst if x % 3 == 0]
Problem 112: Get the elements that are divisible by 5 in a list
python
CopyEdit
def divisible_by_5(lst): return [x for x in lst if x % 5 == 0]
Problem 113: Get the nth largest element in a list
python
CopyEdit
import heapq
def nth_largest(lst, n): return heapq.nlargest(n, lst)[-1]
Problem 114: Get the nth smallest element in a list
python
CopyEdit
import heapq
def nth_smallest(lst, n): return heapq.nsmallest(n, lst)[-1]
Problem 115: Check if a list contains only numeric values
python
CopyEdit
def is_numeric(lst): return all(isinstance(x, (int, float)) for x in lst)
Problem 116: Merge multiple lists into one
python
CopyEdit
def merge_lists(*lists): return [item for sublist in lists for item in sublist]
Problem 117: Check if a string is a valid number
python
CopyEdit
def is_valid_number(s): return s.replace('.', '', 1).isdigit() if s[0] != '-' else
s[1:].replace('.', '', 1).isdigit()
Problem 118: Find the longest palindrome in a list of strings
python
CopyEdit
def longest_palindrome(lst): return max((s for s in lst if s == s[::-1]), key=len,
default='')
Problem 119: Find the longest even number in a list
python
CopyEdit
def longest_even(lst): return max((str(x) for x in lst if x % 2 == 0), key=len,
default='')
Problem 120: Find the sum of all prime numbers in a list
python
CopyEdit
def sum_primes(lst): return sum(x for x in lst if is_prime(x))

You might also like