In Python, a list is a collection of items which can be of different types (integer, float, string, etc.), and it is ordered, mutable, and allows duplicate elements.
Lists are defined by enclosing elements in square brackets []
.
- Ordered
- Lists maintain the order of the elements.
my_list = [1, 2, 3, 4] print(my_list) # Output: [1, 2, 3, 4]
- Mutable
- You can change elements after the list is created.
my_list = [1, 2, 3, 4] my_list[0] = 10 print(my_list) # Output: [10, 2, 3, 4]
- Allows Duplicate Elements
- Lists can have items with the same value.
my_list = [1, 2, 2, 3, 4, 4] print(my_list) # Output: [1, 2, 2, 3, 4, 4]
- Dynamic
- The size of the list can change dynamically as elements are added or removed.
my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4] my_list.pop() print(my_list) # Output: [1, 2, 3]
- Heterogeneous
- Lists can contain elements of different types.
my_list = [1, "hello", 3.14, True] print(my_list) # Output: [1, 'hello', 3.14, True]
- Supports Indexing and Slicing
- Lists support accessing elements via indexing and slicing.
my_list = [1, 2, 3, 4, 5] print(my_list[1]) # Output: 2 print(my_list[1:4]) # Output: [2, 3, 4]
These properties make lists a versatile and powerful data structure in Python.