A list in Python is a versatile and fundamental data structure used to store an ordered collection of items. It is one of the most commonly used data structures for grouping data. Lists are created by placing items inside square brackets [], separated by commas.
Key Characteristics of Lists
- Ordered: The items in a list have a defined order, and that order will not change unless you modify it.
- Mutable: This is a crucial feature. "Mutable" means that you can change the list after it has been created. You can add, remove, or modify its elements directly.
- Allows Duplicates: Lists can contain multiple items with the same value.
- Can Contain Different Data Types: A single list can hold items of different data types, such as integers, strings, and even other lists.
Python
# A list of fruits (all strings)
fruits = ["apple", "banana", "cherry"]
# A list with mixed data types, including a nested list
mixed_list = [1, "hello", 3.14, True, ["another", "list"]]
print(f"A simple list: {fruits}")
print(f"A mixed-type list: {mixed_list}")
Operations with Operators
Concatenation (+)
Combines two lists to create a new, single list.
Python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(f"Concatenation (+): {combined_list}")
# Output: [1, 2, 3, 4, 5, 6]
Repetition (*)
Creates a new list by repeating the original list's elements a specified number of times.
Python
repeated_list = ['a'] * 5
print(f"Repetition (*): {repeated_list}")
# Output: ['a', 'a', 'a', 'a', 'a']
Indexing ([])
Accesses a single item at a specific position (index). Python uses zero-based indexing, so the first item is at index 0. Negative indexing starts from the end, where -1 is the last item.
Python
numbers = [10, 20, 30, 40, 50]
print(f"First item (index 0): {numbers[0]}") # Output: 10
print(f"Last item (index -1): {numbers[-1]}") # Output: 50
Slicing ([:])
Extracts a portion of the list, creating a new list. The syntax is list[start:stop:step]. The start index is inclusive, and the stop index is exclusive.
Python
numbers = [10, 20, 30, 40, 50, 60]
print(f"Slice from index 2 to 4: {numbers[2:5]}") # Output: [30, 40, 50]
print(f"Slice every second element: {numbers[::2]}") # Output: [10, 30, 50]
Membership Testing (in, not in)
Checks if an item exists within a list, returning True or False.
Python
fruits = ["apple", "banana", "cherry"]
print(f"Is 'banana' in the list? {'banana' in fruits}") # Output: True
print(f"Is 'mango' not in the list? {'mango' not in fruits}") # Output: True
Built-in Functions for Lists
len()
Returns the number of items in a list.
Python
numbers = [10, 20, 30, 40]
print(f"Length of the list: {len(numbers)}") # Output: 4
sum(), min(), max()
Returns the sum, minimum, or maximum item in a list. These only work if all items are numbers.
Python
numbers = [5, 2, 8, 1, 9]
print(f"Sum of numbers: {sum(numbers)}") # Output: 25
print(f"Min of numbers: {min(numbers)}") # Output: 1
print(f"Max of numbers: {max(numbers)}") # Output: 9
sorted()
Returns a new, sorted list without modifying the original list.
Python
unsorted_numbers = [3, 1, 4, 1, 5, 9]
sorted_copy = sorted(unsorted_numbers)
print(f"Original list: {unsorted_numbers}")
print(f"New sorted list: {sorted_copy}")
Common List Methods
Adding and Removing Items
- .append(item): Adds a single item to the very end of the list.
Python
fruits = ["apple", "banana"]
fruits.append("cherry")
print(f"After .append('cherry'): {fruits}") # Output: ['apple', 'banana', 'cherry']
- .extend(iterable): Adds all the items from an iterable (like another list) to the end of the list.
Python
fruits = ["apple", "banana"]
fruits.extend(["cherry", "mango"])
print(f"After .extend(): {fruits}") # Output: ['apple', 'banana', 'cherry', 'mango']
- .insert(index, item): Inserts an item at a specified position.
Python
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
print(f"After .insert(1, 'banana'): {fruits}") # Output: ['apple', 'banana', 'cherry']
- .remove(item): Removes the first occurrence of a specified item.
Python
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(f"After .remove('banana'): {fruits}") # Output: ['apple', 'cherry', 'banana']
- .pop(index): Removes and returns the item at a specified index. If no index is given, it removes and returns the last item.
Python
fruits = ["apple", "banana", "cherry"]
removed_fruit = fruits.pop(1)
print(f"Removed fruit: {removed_fruit}, List is now: {fruits}") # Output: Removed fruit: banana, List is now: ['apple', 'cherry']
- .clear(): Removes all items from the list.
Python
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(f"After .clear(): {fruits}") # Output: []
Organizing and Searching
- .sort(): Sorts the items of the list in place (modifies the original list).
Python
numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(f"After .sort(): {numbers}") # Output: [1, 2, 5, 8, 9]
- .reverse(): Reverses the order of the items in place.
Python
numbers = [1, 2, 5, 8, 9]
numbers.reverse()
print(f"After .reverse(): {numbers}") # Output: [9, 8, 5, 2, 1]
- .index(item): Returns the index of the first occurrence of a specified item.
Python
fruits = ["apple", "banana", "cherry"]
print(f"Index of 'cherry': {fruits.index('cherry')}") # Output: 2
- .count(item): Returns the number of times a specified item appears in the list.
Python
numbers = [1, 2, 8, 2, 5, 2]
print(f"Count of '2': {numbers.count(2)}") # Output: 3
Copying
- .copy(): Returns a shallow copy of the list. This is important when you want to modify a copy without affecting the original list.
Python
original_list = [1, 2, 3]
copied_list = original_list.copy()
copied_list.append(4)
print(f"Original list: {original_list}") # Output: [1, 2, 3]
print(f"Copied list: {copied_list}") # Output: [1, 2, 3, 4]