A list in Python is a versatile and fundamental data type 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. If you add new items to a list, they will be placed at the end.
- 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.
- Allows Duplicates: Lists can contain 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.
Operations on Lists
- Concatenation (+): Combines two lists to create a new, single list.
- Repetition (*): Creates a new list by repeating the original list's elements a specified number of times.
- Indexing: Accesses a single item at a specific position (index). Like strings, lists use zero-based indexing.
- Slicing: Extracts a portion of the list, creating a new list.
- Membership Testing (in, not in): Checks if an item exists within a list, returning True or False.
Built-in Functions for Lists
- len(): Returns the number of items in a list.
- sum(): Returns the sum of all items in a list (only works if all items are numbers).
- min() / max(): Returns the minimum or maximum item in a list.
- sorted(): Returns a new, sorted list without modifying the original.
Common List Methods
Methods are functions called on a list object itself (e.g., my_list.append()).
Adding and Removing Items
- .append(item): Adds a single item to the very end of the list.
- .extend(iterable): Adds all the items from an iterable (like another list) to the end of the list.
- .insert(index, item): Inserts an item at a specified position.
- .remove(item): Removes the first occurrence of a specified item.
- .pop(index): Removes and returns the item at a specified index. If no index is given, it removes and returns the last item.
- .clear(): Removes all items from the list.
Organizing and Searching
- .sort(): Sorts the items of the list in place (modifies the original list).
- .reverse(): Reverses the order of the items in place.
- .index(item): Returns the index of the first occurrence of a specified item.
- .count(item): Returns the number of times a specified item appears in the list.
Copying
- .copy(): Returns a shallow copy of the list. This is useful when you want to modify a copy without affecting the original list.
# --- 1. List Creation ---
# Lists are ordered, mutable collections of items in square brackets.
empty_list = []
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "hello", 3.14, True]
print(f"A list of fruits: {fruits}")
# --- 2. Basic Operations ---
print("\n--- Basic Operations ---")
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Concatenation (+)
combined_list = list1 + list2
print(f"Concatenation: {combined_list}")
# Repetition (*)
repeated_list = list1 * 3
print(f"Repetition: {repeated_list}")
# --- 3. Indexing and Slicing ---
# Accessing items in a list.
numbers = [10, 20, 30, 40, 50, 60]
print("\n--- Indexing and Slicing ---")
print(f"Original List: {numbers}")
print(f"First item (index 0): {numbers[0]}")
print(f"Last item (index -1): {numbers[-1]}")
print(f"Slice from index 2 to 4: {numbers[2:5]}")
# --- 4. Modifying a List (Mutability) ---
print("\n--- Modifying a List ---")
fruits = ["apple", "banana", "cherry"]
print(f"Original fruits: {fruits}")
# Change an item
fruits[1] = "blueberry"
print(f"After changing an item: {fruits}")
# --- 5. List Methods: Adding and Removing ---
print("\n--- List Methods: Adding and Removing ---")
# .append() adds an item to the end
fruits.append("orange")
print(f"After .append('orange'): {fruits}")
# .insert() adds an item at a specific index
fruits.insert(1, "mango")
print(f"After .insert(1, 'mango'): {fruits}")
# .remove() removes the first occurrence of a value
fruits.remove("cherry")
print(f"After .remove('cherry'): {fruits}")
# .pop() removes and returns an item at an index (default is the last)
popped_fruit = fruits.pop()
print(f"Popped item: {popped_fruit}, List is now: {fruits}")
# --- 6. List Methods: Organizing and Searching ---
print("\n--- List Methods: Organizing and Searching ---")
numbers = [5, 2, 8, 1, 9]
print(f"Original numbers: {numbers}")
# .sort() modifies the list in place
numbers.sort()
print(f"After .sort(): {numbers}")
# .reverse() modifies the list in place
numbers.reverse()
print(f"After .reverse(): {numbers}")
# .index() finds the position of an item
print(f"Index of '8': {numbers.index(8)}")
# .count() counts occurrences of an item
fruits.append("mango")
print(f"Count of 'mango' in {fruits}: {fruits.count('mango')}")
# --- 7. Built-in Functions with Lists ---
print("\n--- Built-in Functions with Lists ---")
print(f"Length of fruits list: {len(fruits)}")
print(f"Sum of numbers list: {sum(numbers)}")
print(f"Max of numbers list: {max(numbers)}")
print(f"Min of numbers list: {min(numbers)}")
# sorted() returns a new sorted list, leaving the original unchanged
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}")