Python List Manipulation Exercises
Python List Manipulation Exercises
To count strings that are at least two characters long and have the same first and last character, iterate over the list and check each condition: ```python sample_list = ['abc', 'xyz', 'aba', '1221'] result = len([s for s in sample_list if len(s) > 1 and s[0] == s[-1]]) ``` This code iterates through each string in the list, checking if the length is greater than 1 and if the first and last characters match, yielding the expected result of 2 .
To generalize creating unique lists across any iterable, you can create a reusable function or class. Using set for uniqueness across iterable types: ```python def unique(iterable): return list(set(iterable)) ``` This function handles any iterable, converting it to a unique list. This abstraction helps in software design by promoting code reuse, simplicity, and reducing error-prone redundancy by enabling one functionality across multiple data structures .
Finding the second largest number requires sorting or other comparative techniques like iterating over the list while maintaining top two largest numbers. A simple way is: ```python def second_largest(nums): first = second = float('-inf') for number in nums: if number > first: first, second = number, first elif first > number > second: second = number return second # Example usage: second_largest([5, 8, 12, 3, 9]) ``` This method iterates once (O(n) complexity), adjusting `first` and `second` appropriately. For lists with only two elements, ensure both are unique for a valid second largest .
To find the index of an element in a list, you can use the `list.index()` method, which iterates through the list to find the element, returning the index of its first occurrence: ```python sample_list = ['Red', 'Green', 'White'] index = sample_list.index('Green') ``` The method performs a linear search, meaning its time complexity is O(n). Python internally stops the search upon finding the first matching element, making it efficient for lists with a small number of elements .
To append one list to another, you use the `list.extend()` method, which mutates the first list in place by adding elements from the second list: ```python list1 = [1, 2, 3] list2 = [4, 5] list1.extend(list2) ``` This results in `list1` holding `[1, 2, 3, 4, 5]`. The `extend` method modifies the original `list1` without creating a new list, unlike concatenation which results in list copying .
When modifying lists in place, consider side effects and data integrity as the original list changes, potentially impacting other code using it. Ensure you document or adhere to immutability principles if objects should not change unexpectedly: ```python # Example of list mutation lst = [1, 2, 3] lst.append(4) ``` Predictability can be enhanced by cloning data before operations if side-effects are undesirable: ```python cloned_lst = lst[:] ``` Maintaining data integrity is crucial, especially in larger, more complex systems where such mutations might result in elusive bugs .
Two lists can be combined in Python using the `+` operator or the `list.extend()` method. For example: Using the `+` operator: ```python list1 = [1, 2, 3] list2 = [4, 5] combined_list = list1 + list2 ``` Using `extend()` method: ```python list1 = [1, 2, 3] list1.extend([4, 5]) ``` Both result in the list `[1, 2, 3, 4, 5]`. The `+` operator creates a new list, while `extend()` modifies the first list in place .
You can remove elements from specific indices using a list comprehension that excludes these indices. For the sample list `['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']`, if you remove the 0th, 4th, and 5th elements, the program would be: ```python sample_list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] result = [item for i, item in enumerate(sample_list) if i not in (0, 4, 5)] ``` The resulting list would be `['Green', 'White', 'Black']` .
A Python function that filters duplicates from a list can be implemented using a set, as sets inherently prevent duplicate entries. Here is a sample implementation: ```python def remove_duplicates(lst): return list(set(lst)) ``` This function first converts the list to a set, which removes duplicates, and then back to a list. The complexity of this solution is O(n) because it iterates over the input list to convert it to a set .
An efficient way to remove duplicates while maintaining order is to use a dictionary since Python 3.7+ maintains insertion order: ```python def remove_duplicates(lst): return list(dict.fromkeys(lst)) ``` This implementation utilizes the dictionary keys to maintain unique entries, retaining their original order. The time complexity is O(n), as both constructing the dictionary and converting it back to a list involves single passes over the data .