๐ Lists in Python
Lists in Python are ordered collections of items that can be of any data type. They are mutable, meaning you can change their content after creation. Lists are defined using square brackets [].
lists.py
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # Output: bananaList comprehensions offer a concise way to create lists:
list_comprehension.py
squares = [x**2 for x in range(1, 11)]
print(squares) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]- You can check available methods using:
dir(fruits) # short info
help(fruits) # detailed info๐ฉป List Operations
Lists support various operations:
list_operations.py
- len(fruits) # Get the number of items
- "apple" in fruits # Check if an item exists
- fruits + ["kiwi", "mango"] # Concatenate lists
- fruits * 2 # Repeat the list
- fruits[1:3] # Slice the list (from index 1 to 2)๐ช List Methods
Python provides several built-in methods for lists:
list_methods.py
- fruits[0] # Access item by index
- fruits.append("orange") # Add item
- fruits.remove("banana") # Remove item
- fruits.insert(1, "grape") # Insert at position
- fruits.sort() # Sort the list
- fruits.reverse() # Reverse the list
- fruits.clear() # Remove all items
- fruits.index("cherry") # Find index of an item
- fruits.count("apple") # Count occurrences of an item
- fruits.pop() # Remove and return the last item
- fruits.extend(["kiwi", "mango"]) # Extend list with another list
- fruits.copy() # Create a shallow copy of the list๐งฉ Nested Lists
Lists can contain other lists, allowing for multi-dimensional data structures:
nested_lists.py
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # Output: 6๐งฎ List Iteration
You can iterate through the items in a list using a for loop:
list_iteration.py
for fruit in fruits:
print(fruit) # apple banana cherryYou can also use list comprehensions for concise iteration:
list_comprehension.py
uppercase_fruits = [fruit.upper() for fruit in fruits]
print(uppercase_fruits) # Output: ['APPLE', 'BANANA', 'CHERRY']๐งฐ List Conversion
You can convert other data types to lists, such as strings or tuples:
list_conversion.py
# String to list
sentence = "Hello World"
words = sentence.split()
print(words) # Output: ['Hello', 'World']
# Tuple to list
coordinates = (10, 20, 30)
coords_list = list(coordinates)
print(coords_list) # Output: [10, 20, 30]
# Set to list
my_set = {1, 2, 3}
set_list = list(my_set)
print(set_list) # Output: [1, 2, 3] (order may vary)Last updated on