Practical List Manipulation Examples
Now that you have a solid understanding of Python lists and how to define custom list functions, let's explore some practical examples of list manipulation techniques.
Filtering List Elements
Suppose you have a list of numbers and you want to create a new list containing only the even numbers. You can define a custom function to achieve this:
def filter_even(numbers):
return [num for num in numbers if num % 2 == 0]
my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter_even(my_numbers)
print(even_numbers) ## Output: [2, 4, 6, 8, 10]
In this example, the filter_even()
function uses a list comprehension to create a new list containing only the even numbers from the input list.
Suppose you have a list of strings and you want to create a new list containing the uppercase versions of those strings. You can define a custom function to do this:
def uppercase_strings(strings):
return [s.upper() for s in strings]
my_strings = ['apple', 'banana', 'cherry', 'date']
uppercase_list = uppercase_strings(my_strings)
print(uppercase_list) ## Output: ['APPLE', 'BANANA', 'CHERRY', 'DATE']
In this example, the uppercase_strings()
function uses a list comprehension to create a new list containing the uppercase versions of the input strings.
Suppose you have a list of numbers and you want to calculate the sum, average, and maximum value of the list. You can define custom functions to perform these operations:
def sum_list(numbers):
return sum(numbers)
def average_list(numbers):
return sum(numbers) / len(numbers)
def max_list(numbers):
return max(numbers)
my_numbers = [10, 20, 30, 40, 50]
total = sum_list(my_numbers)
avg = average_list(my_numbers)
maximum = max_list(my_numbers)
print(f"Sum: {total}") ## Output: Sum: 150
print(f"Average: {avg}") ## Output: Average: 30.0
print(f"Maximum: {maximum}") ## Output: Maximum: 50
In this example, the sum_list()
, average_list()
, and max_list()
functions perform the respective aggregate operations on the input list of numbers.
By combining your understanding of Python lists and the ability to define custom list functions, you can create powerful and flexible solutions for a wide range of data processing and manipulation tasks.