Lists are one of the most versatile and commonly used data structures in Python. They provide a flexible way to store and manipulate collections of items. Whether you're working with numbers, text, or any other data, lists can be your go-to tool. In this article, we will dive deep into lists, exploring their features, operations, and best practices with practical examples.
-
Creating a List:
-
Example 1: Creating a list of numbers
numbers = [1, 2, 3, 4, 5] -
Example 2: Creating a list of strings
fruits = ["apple", "banana", "orange"]
-
-
Accessing List Elements:
-
Example 1: Accessing individual elements by index
print(numbers[0]) # Output: 1print(fruits[1]) # Output: "banana" -
Example 2: Slicing a list to retrieve a sublist
print(numbers[1:4]) # Output: [2, 3, 4]
-
-
Modifying List Elements:
-
Example 1: Modifying an element at a specific index
fruits[2] = "grape"print(fruits) # Output: ["apple", "banana", "grape"] -
Example 2: Appending an element to the end of the list
numbers.append(6) print(numbers) # Output: [1, 2, 3, 4, 5, 6]
-
-
List Operations:
-
Example 1: Concatenating two lists
combined = numbers + fruitsprint(combined) # Output: [1, 2, 3, 4, 5, "apple", "banana", "grape"] -
Example 2: Checking if an element exists in a list
print("apple" in fruits) # Output: True
-
-
List Methods:
-
Example 1: Sorting a list
numbers.sort()print(numbers) # Output: [1, 2, 3, 4, 5] -
Example 2: Removing an element from a list
fruits.remove("banana")print(fruits) # Output: ["apple", "grape"]
-
-
List Comprehensions:
-
Example 1: Creating a new list based on an existing list
squared = [num ** 2 for num in numbers]print(squared) # Output: [1, 4, 9, 16, 25] -
Example 2: Filtering a list using a condition
evens = [num for num in numbers if num % 2 == 0]print(evens) # Output: [2, 4]
-