List

Top 10 Python examples for Lists related tasks

Python, boasts of its easy-to-understand syntax and wide range of data types. Among these data types, python list data type stands out due to its versatility. This blog post presents top python examples for lists, diving deep into Python lists, exploring their features, methods, and potential use cases.

Python Examples for Lists

Example 1: Finding the Maximum Element

Python
numbers = [14, 8, 23, 5, 42, 17]
max_number = max(numbers)
print("The maximum number in the list is:", max_number)

Description: This example demonstrates how to find the maximum element in a list using the max() function.

Example 2: Reversing a List

Python
fruits = ["apple", "banana", "cherry", "date"]
reversed_fruits = fruits[::-1]
print("Reversed list of fruits:", reversed_fruits)

Description: This example shows how to reverse the elements of a list using slicing.

Example 3: List Comprehension for Squares

Python
numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print("List of squares:", squares)

Description: List comprehension is used to create a new list containing the squares of numbers in the original list.

Example 4: Filtering Even Numbers

Python
numbers = [11, 20, 35, 42, 57, 68]
even_numbers = [x for x in numbers if x % 2 == 0]
print("List of even numbers:", even_numbers)

Description: List comprehension is used to filter and create a new list containing only even numbers.

Example 5: Concatenating Lists

Python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print("Concatenated list:", combined_list)

Description: This example demonstrates how to concatenate two lists using the + operator.

Example 6: Removing Duplicates

Python
numbers = [5, 2, 8, 2, 5, 9, 8, 10]
unique_numbers = list(set(numbers))
print("List with duplicates removed:", unique_numbers)

Description: By converting the list to a set and back to a list, duplicates are removed.

Example 7: Sorting a List

Python
fruits = ["apple", "banana", "cherry", "date"]
sorted_fruits = sorted(fruits)
print("Sorted list of fruits:", sorted_fruits)

Description: The sorted() function is used to sort the elements of a list.

Example 8: List Length

Python
colors = ["red", "green", "blue", "yellow"]
num_colors = len(colors)
print("Number of colors in the list:", num_colors)

Description: The len() function is used to find the length of a list.

Example 9: List Slicing

Python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
subset = numbers[2:7]
print("Sliced list:", subset)

Description: This example shows how to create a sublist using list slicing.

Example 10: Updating List Elements

Python
scores = [85, 92, 78, 95, 88]
scores[2] = 80
print("Updated list of scores:", scores)

Description: This example demonstrates how to update a specific element in a list by index.