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 We can access elements using indexing (starting at 0 for the first element).
Python
fruits = ['apple', 'banana', 'cherry'] # Accessing elements print(fruits[0]) # Output: apple print(fruits[-1]) # Output: cherry (negative indexing starts from the end)