4.1 Lists

4.1 Lists

Exploring lists, the most versatile collection structure. We will see how they are created, how to access and modify their elements, and their most common methods.

Lists are the most flexible and frequently used collection structures in Python. They are incredibly powerful and allow you to store an ordered sequence of items.

Key features of lists:

  • Ordered: Items maintain the order in which they were inserted. They have indices starting from 0.
  • Mutable/Changeable: You can add, remove, or change items after the list is created. This means changes are made "in-place," on the list itself, without needing to create a new one.
  • Allow Duplicate Items: You can have the same value appear multiple times in a list.
  • Can Contain Different Data Types: A list can contain integers, strings, Booleans, and even other lists or dictionaries.
Lists are declared using square brackets `[]`, with items separated by commas.

Creating a List

# Creating lists with various types of items

# List of integers
numbers = [1, 2, 3, 4, 5]
print(f"List of numbers: {numbers}, Type: {type(numbers)}")

# List of strings
names = ["Alexander", "Maria", "John", "Helen"]
print(f"List of names: {names}")

# List of mixed data types
mixed_list = [10, "Python", True, 3.14, None]
print(f"Mixed list: {mixed_list}")

# List with duplicate items
duplicate_items = [1, 2, 2, 3, 1, 4]
print(f"List with duplicates: {duplicate_items}")

# Creating an empty list
empty_list = []
print(f"Empty list: {empty_list}")

# Creating a list from an iterable (e.g., a string) using the list() constructor
word_to_list = list("Python")
print(f"Word to list of characters: {word_to_list}") # ['P', 'y', 't', 'h', 'o', 'n']

Accessing Items (Indexing) and Slicing

Like strings, items in a list have an index, starting from 0 for the first item. You can use positive and negative indices.
# Accessing list items with indexing
fruits = ["apple", "banana", "cherry", "orange", "pear"]

print(f"First fruit (index 0): {fruits[0]}")
print(f"Third fruit (index 2): {fruits[2]}")
print(f"Last fruit (index -1): {fruits[-1]}")
print(f"Second to last fruit (index -2): {fruits[-2]}")

# Note: If you try to access an index that does not exist, you will get an IndexError.
try:
    print(fruits[5]) # Will cause an IndexError
except IndexError:
    print("Error: Index 5 is out of bounds for the list.")
Slicing allows you to get a subset (a "piece") of a list. The syntax is `[start:end:step]`, just like with strings.
# Slicing a list
number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90]

print(f"From the 2nd to the 4th item (indices 1-3): {number_list[1:4]}")
print(f"From the beginning up to the 3rd item (indices 0-2): {number_list[:3]}")
print(f"From the 4th item (index 3) to the end: {number_list[3:]}")
print(f"The whole list (a copy): {number_list[:]}")
print(f"Reversed list: {number_list[::-1]}")
print(f"Every second item: {number_list[::2]}")

Modifying a List

Lists are mutable, which means you can add, remove, change, or reorder items after they are created.
# Modifying a list
my_shopping_list = ["milk", "bread", "eggs"]
print(f"Initial list: {my_shopping_list}")

# Changing an item
my_shopping_list[1] = "cheese"
print(f"After changing bread to cheese: {my_shopping_list}")

# Adding items
my_shopping_list.append("fruits")
print(f"After append('fruits'): {my_shopping_list}")

my_shopping_list.insert(0, "coffee")
print(f"After insert(0, 'coffee'): {my_shopping_list}")

other_items = ["rice", "pasta"]
my_shopping_list.extend(other_items)
print(f"After extend(['rice', 'pasta']): {my_shopping_list}")

print("-" * 30)

# Removing items
my_shopping_list.remove("milk")
print(f"After remove('milk'): {my_shopping_list}")

last_removed_item = my_shopping_list.pop()
print(f"After pop() (removed '{last_removed_item}'): {my_shopping_list}")

removed_from_index = my_shopping_list.pop(1)
print(f"After pop(1) (removed '{removed_from_index}'): {my_shopping_list}")

del my_shopping_list[0]
print(f"After del my_shopping_list[0]: {my_shopping_list}")

print("-" * 30)

# Other methods
numbers_to_sort = [5, 2, 8, 1, 9]
print(f"Initial numbers to sort: {numbers_to_sort}")
numbers_to_sort.sort()
print(f"Sorted numbers: {numbers_to_sort}")

numbers_to_sort.reverse()
print(f"Reversed numbers: {numbers_to_sort}")

count_of_2 = [1, 2, 2, 3, 2].count(2)
print(f"The number 2 appears {count_of_2} times.")

index_of_8 = [5, 2, 8, 1, 9].index(8)
print(f"The index of 8 is: {index_of_8}")

my_shopping_list.clear()
print(f"After clear(): {my_shopping_list}")

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.