Python Beginner

Python Lists: Working with Ordered Collections

CodingerWeb
CodingerWeb
19 views 35 min read

Understanding Python Lists

Lists are ordered collections that can store multiple items. They are mutable, meaning you can change their contents after creation.

Creating Lists


# Empty list
empty_list = []
also_empty = list()

# List with items
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, 3.14, True]

print(fruits)   # ['apple', 'banana', 'orange']
print(numbers)  # [1, 2, 3, 4, 5]
print(mixed)    # ['hello', 42, 3.14, True]

Accessing List Elements


fruits = ["apple", "banana", "orange", "grape", "kiwi"]

# Positive indexing (starts from 0)
print(fruits[0])   # apple
print(fruits[1])   # banana
print(fruits[4])   # kiwi

# Negative indexing (starts from -1)
print(fruits[-1])  # kiwi (last item)
print(fruits[-2])  # grape (second to last)

# Slicing
print(fruits[1:4])   # ['banana', 'orange', 'grape']
print(fruits[:3])    # ['apple', 'banana', 'orange']
print(fruits[2:])    # ['orange', 'grape', 'kiwi']
print(fruits[::2])   # ['apple', 'orange', 'kiwi'] (every 2nd item)

Modifying Lists


fruits = ["apple", "banana", "orange"]

# Changing items
fruits[1] = "blueberry"
print(fruits)  # ['apple', 'blueberry', 'orange']

# Adding items
fruits.append("grape")        # Add to end
print(fruits)  # ['apple', 'blueberry', 'orange', 'grape']

fruits.insert(1, "mango")     # Insert at index 1
print(fruits)  # ['apple', 'mango', 'blueberry', 'orange', 'grape']

# Extending lists
more_fruits = ["kiwi", "pear"]
fruits.extend(more_fruits)
print(fruits)  # ['apple', 'mango', 'blueberry', 'orange', 'grape', 'kiwi', 'pear']

# Removing items
fruits.remove("mango")        # Remove by value
print(fruits)

removed_item = fruits.pop()   # Remove and return last item
print(f"Removed: {removed_item}")
print(fruits)

del fruits[0]                 # Remove by index
print(fruits)

List Methods


numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# Sorting
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

numbers.sort(reverse=True)
print(numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

# Other useful methods
fruits = ["apple", "banana", "apple", "orange"]

print(fruits.count("apple"))  # 2 (count occurrences)
print(fruits.index("banana")) # 1 (find index)

fruits.reverse()
print(fruits)  # ['orange', 'apple', 'banana', 'apple']

# Copy lists
fruits_copy = fruits.copy()
# or
fruits_copy2 = fruits[:]

List Comprehensions

A concise way to create lists:


# Basic list comprehension
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# With condition
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)  # [4, 16, 36, 64, 100]

# String manipulation
words = ["hello", "world", "python"]
uppercase = [word.upper() for word in words]
print(uppercase)  # ['HELLO', 'WORLD', 'PYTHON']

# Nested list comprehension
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)  # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Working with Lists


# Length of list
fruits = ["apple", "banana", "orange"]
print(len(fruits))  # 3

# Check if item exists
if "apple" in fruits:
    print("Apple is in the list")

# Iterate through list
for fruit in fruits:
    print(f"I like {fruit}")

# Iterate with index
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# Join list items
sentence = " ".join(["Python", "is", "awesome"])
print(sentence)  # Python is awesome

# Split string into list
words = "Hello world Python".split()
print(words)  # ['Hello', 'world', 'Python']

Nested Lists


# 2D list (list of lists)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Accessing nested elements
print(matrix[0])     # [1, 2, 3]
print(matrix[1][2])  # 6

# Iterating through 2D list
for row in matrix:
    for item in row:
        print(item, end=" ")
    print()  # New line after each row

Practice Exercise

Create a to-do list manager:


def todo_manager():
    """Simple to-do list manager"""
    todos = []
    
    while True:
        print("
--- To-Do List Manager ---")
        print("1. Add task")
        print("2. View tasks")
        print("3. Mark task as complete")
        print("4. Remove task")
        print("5. Quit")
        
        choice = input("Choose an option (1-5): ")
        
        if choice == "1":
            task = input("Enter a new task: ")
            todos.append({"task": task, "completed": False})
            print(f"Added: {task}")
            
        elif choice == "2":
            if not todos:
                print("No tasks yet!")
            else:
                print("
Your tasks:")
                for i, todo in enumerate(todos, 1):
                    status = "✓" if todo["completed"] else "○"
                    print(f"{i}. {status} {todo['task']}")
                    
        elif choice == "3":
            if not todos:
                print("No tasks to complete!")
            else:
                try:
                    task_num = int(input("Enter task number to complete: ")) - 1
                    if 0 <= task_num < len(todos):
                        todos[task_num]["completed"] = True
                        print(f"Marked as complete: {todos[task_num]['task']}")
                    else:
                        print("Invalid task number!")
                except ValueError:
                    print("Please enter a valid number!")
                    
        elif choice == "4":
            if not todos:
                print("No tasks to remove!")
            else:
                try:
                    task_num = int(input("Enter task number to remove: ")) - 1
                    if 0 <= task_num < len(todos):
                        removed = todos.pop(task_num)
                        print(f"Removed: {removed['task']}")
                    else:
                        print("Invalid task number!")
                except ValueError:
                    print("Please enter a valid number!")
                    
        elif choice == "5":
            print("Goodbye!")
            break
            
        else:
            print("Invalid choice! Please try again.")

# Run the to-do manager
todo_manager()