Python List Exercises and Solutions
Python List Exercises and Solutions
You can concatenate two lists index-wise using a list comprehension with a 'zip()' function: '[i + j for i, j in zip(list1, list2)]'. For the lists ['M', 'na', 'i', 'Ke'] and ['y', 'me', 's', 'lly'], the output is ['My', 'name', 'is', 'Kelly'].
Use the 'zip()' function with slicing to reverse the second list: 'for x, y in zip(list1, list2[::-1])'. For lists [10, 20, 30, 40] and [100, 200, 300, 400], the paired output is 10 400, 20 300, 30 200, 40 100 .
Remove empty strings using list comprehension with a condition: '[s for s in list1 if s]'. This applied to ['Mike', '', 'Emma', 'Kelly', '', 'Brad'] results in ['Mike', 'Emma', 'Kelly', 'Brad'].
Count such strings using a list comprehension with a condition: 'len([s for s in list1 if len(s) >= 3 and s[0] == s[-1]])'. For ['abc', 'xyz', 'aba', '1221', 'xyyxz', 'AA'], there are 2 strings ('aba', '1221') fulfilling the criteria .
To concatenate two lists in all possible orders, use a nested loop within a list comprehension: '[x + y for x in list1 for y in list2]'. For ['Hello ', 'take '] and ['Dear', 'Sir'], the output would be ['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir'].
Use a list comprehension to iterate over each element and apply the square operation: '[x ** 2 for x in aList]'. Applying this to [1, 2, 3, 4, 5, 6, 7] results in [1, 4, 9, 16, 25, 36, 49].
Access the desired position by indexing into the nested list, then use 'insert()': 'list1[2][2].insert(2, 7000)'. For the list [10, 20, [300, 400, [5000, 6000], 500], 30, 40], this process inserts 7000, resulting in [10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40].
To reverse a list in Python, you can use the slicing method with a step of -1: 'aList[::-1]', where 'aList' is the list you want to reverse. Applying this to [100, 200, 300, 400, 500] results in [500, 400, 300, 200, 100].
To replace the first occurrence of a specific value in a list, you can use the 'index()' method to find the position of the value and then update it. For the list [5, 10, 15, 20, 25, 50, 20], use 'list1[list1.index(20)] = 200'. This gives [5, 10, 15, 200, 25, 50, 20].
Navigate to the target sublist with appropriate indexing and use 'extend()': 'list1[2][1][2].extend(sub_list)'. Applying this to [['a', 'b', ['c', ['d', 'e', ['f', 'g'], 'k'], 'l'], 'm', 'n']] with ['h', 'i', 'j'], the output is ['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n'].