A list in Python is an ordered collection of elements. Lists can store items of any data type and are mutable, meaning their values can be changed after the list is created. They are defined by placing items inside square brackets, separated by commas.
Lists are created by enclosing elements in square brackets.
# List Example fruits = ["apple", "banana", "cherry"] print(fruits) # Output: ['apple', 'banana', 'cherry']
You can access list elements by their index (starting from 0).
# Accessing Elements fruits = ["apple", "banana", "cherry"] print(fruits[0]) # Access first element print(fruits[1]) # Access second element # Output: # apple # banana
Lists are mutable, which means you can modify the values of the elements.
# Modifying Elements fruits = ["apple", "banana", "cherry"] fruits[1] = "blueberry" # Change second element print(fruits) # Output: ['apple', 'blueberry', 'cherry']
You can add items to a list using methods like append(), insert(), and extend().
# Adding Elements
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Adds to the end
fruits.insert(1, "kiwi") # Inserts at specified index
print(fruits)
# Output: ['apple', 'kiwi', 'banana', 'cherry', 'orange']
You can remove items from a list using methods like remove(), pop(), or del.
# Removing Elements
fruits = ["apple", "banana", "cherry", "orange"]
fruits.remove("banana") # Removes by value
fruits.pop(1) # Removes by index
del fruits[0] # Removes by index
print(fruits)
# Output: ['cherry']
You can extract a portion of a list using slicing. The syntax is list[start:end], where the start index is inclusive and the end index is exclusive.
# List Slicing fruits = ["apple", "banana", "cherry", "orange"] print(fruits[1:3]) # From index 1 to 2 (3 is excluded) # Output: ['banana', 'cherry']
You can get the length of a list using the len() function.
# List Length fruits = ["apple", "banana", "cherry"] print(len(fruits)) # Output: 3
Lists can contain other lists as elements, creating a nested structure.
# Nested Lists matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(matrix[1]) # Access the second row # Output: [4, 5, 6]
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!