List in Python
In Python, a list is a collection data type that is mutable, ordered, and allows duplicate elements. Lists are commonly used to store multiple items in a single variable. Here's an explanation of its key features and how to work with lists:
Key Features
- Ordered: The elements in a list have a defined order, which will not change unless explicitly modified.
- Mutable: You can change the content of a list after it is created (e.g., add, remove, or modify elements).
- Allows Duplicates: A list can contain duplicate elements.
- Dynamic: Lists can grow or shrink in size, and they can hold elements of different data types.
Creating a List A list is created using square brackets [].
Python
# Empty list my_list = [] # List with elements fruits = ['apple', 'banana', 'cherry'] # Mixed data types mixed_list = [1, 'hello', 3.14, True]
Accessing Elements in a list We can access list elements using indexing.
- Indexing in Python starts from 0 for the first element.
- A list with n elements will have valid indices from 0 to n-1.
- Accessing an index out of range → raises an IndexError.
- Index must be an integer (using float or string raises TypeError).
- Python also supports negative indexing.
Python
fruits = ['apple', 'banana', 'cherry'] # Accessing elements print(fruits[0]) # Output: apple print(fruits[-1]) # Output: cherry (negative indexing starts from the end)
Iterate over List Items Iteration means going through each element of a list one by one.
Python
numbers = [10, 20, 30, 40]
# Iterate
for num in numbers:
print(num) Output 10
20
30
40
del keyword with List in Python We can use the del keyword to delete one or more elements from a list.
- It works with index and slicing.
- We can also delete the entire list using del.
Example: Delete a Single Item (by index).
Python
fruits = ["apple", "banana", "cherry", "mango"] # Delete item at index 1 del fruits[1] print(fruits) # ['apple', 'cherry', 'mango']