PyGuide

Learn Python with practical tutorials and code examples

Working with Lists in Python: A Complete Guide

Lists are one of the most fundamental and versatile data structures in Python. They allow you to store multiple items in a single variable and are essential for most Python programs. In this tutorial, we'll explore everything you need to know about Python lists.

What are Lists? #

A list is an ordered collection of items (elements) that can be of different data types. Lists are:

  • Mutable: You can change their contents after creation
  • Ordered: Items have a defined order that won't change
  • Allow duplicates: The same value can appear multiple times

Creating Lists #

Empty Lists #

# Creating an empty list
empty_list = []
another_empty_list = list()

print(empty_list)  # Output: []
print(type(empty_list))  # Output: <class 'list'>

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Lists with Initial Values #

# List with different data types
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange", "grape"]
mixed = [1, "hello", 3.14, True, None]

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

Creating Lists from Other Sequences #

# From a string
letters = list("python")
print(letters)  # Output: ['p', 'y', 't', 'h', 'o', 'n']

# From a range
even_numbers = list(range(0, 11, 2))
print(even_numbers)  # Output: [0, 2, 4, 6, 8, 10]

Accessing List Elements #

Indexing #

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

# Positive indexing (from the beginning)
print(fruits[0])   # Output: apple
print(fruits[1])   # Output: banana
print(fruits[3])   # Output: grape

# Negative indexing (from the end)
print(fruits[-1])  # Output: grape
print(fruits[-2])  # Output: orange

Slicing #

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

# Basic slicing [start:end]
print(numbers[2:5])    # Output: [2, 3, 4]
print(numbers[:4])     # Output: [0, 1, 2, 3]
print(numbers[6:])     # Output: [6, 7, 8, 9]

# Slicing with step [start:end:step]
print(numbers[::2])    # Output: [0, 2, 4, 6, 8]
print(numbers[1::2])   # Output: [1, 3, 5, 7, 9]
print(numbers[::-1])   # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Modifying Lists #

Changing Single Elements #

fruits = ["apple", "banana", "orange"]
fruits[1] = "blueberry"
print(fruits)  # Output: ['apple', 'blueberry', 'orange']

Changing Multiple Elements #

numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [20, 30, 40]
print(numbers)  # Output: [1, 20, 30, 40, 5]

List Methods #

Adding Elements #

append() - Add single element to the end #

fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)  # Output: ['apple', 'banana', 'orange']

insert() - Add element at specific position #

fruits = ["apple", "banana", "orange"]
fruits.insert(1, "mango")
print(fruits)  # Output: ['apple', 'mango', 'banana', 'orange']

extend() - Add multiple elements #

fruits = ["apple", "banana"]
more_fruits = ["orange", "grape"]
fruits.extend(more_fruits)
print(fruits)  # Output: ['apple', 'banana', 'orange', 'grape']

Removing Elements #

remove() - Remove first occurrence of value #

fruits = ["apple", "banana", "orange", "banana"]
fruits.remove("banana")
print(fruits)  # Output: ['apple', 'orange', 'banana']

pop() - Remove and return element at index #

fruits = ["apple", "banana", "orange"]
removed = fruits.pop(1)
print(f"Removed: {removed}")  # Output: Removed: banana
print(fruits)  # Output: ['apple', 'orange']

# pop() without index removes last element
last = fruits.pop()
print(f"Last: {last}")  # Output: Last: orange

clear() - Remove all elements #

fruits = ["apple", "banana", "orange"]
fruits.clear()
print(fruits)  # Output: []

Finding Elements #

index() - Find index of first occurrence #

fruits = ["apple", "banana", "orange", "banana"]
index = fruits.index("banana")
print(index)  # Output: 1

count() - Count occurrences #

numbers = [1, 2, 3, 2, 4, 2, 5]
count = numbers.count(2)
print(count)  # Output: 3

Sorting and Reversing #

sort() - Sort list in place #

numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers)  # Output: [1, 1, 2, 3, 4, 5, 9]

# Sort in descending order
numbers.sort(reverse=True)
print(numbers)  # Output: [9, 5, 4, 3, 2, 1, 1]

reverse() - Reverse list in place #

fruits = ["apple", "banana", "orange"]
fruits.reverse()
print(fruits)  # Output: ['orange', 'banana', 'apple']

sorted() - Return new sorted list #

numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 1, 2, 3, 4, 5, 9]
print(numbers)  # Output: [3, 1, 4, 1, 5, 9, 2] (unchanged)

List Operations #

Concatenation #

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined)  # Output: [1, 2, 3, 4, 5, 6]

Repetition #

numbers = [1, 2, 3]
repeated = numbers * 3
print(repeated)  # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

Membership Testing #

fruits = ["apple", "banana", "orange"]
print("apple" in fruits)      # Output: True
print("grape" in fruits)      # Output: False
print("mango" not in fruits)  # Output: True

List Comprehensions #

List comprehensions provide a concise way to create lists:

Basic List Comprehension #

# Traditional approach
squares = []
for x in range(10):
    squares.append(x**2)

# List comprehension
squares = [x**2 for x in range(10)]
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

List Comprehension with Conditions #

# Even numbers only
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # Output: [0, 4, 16, 36, 64]

# String manipulation
words = ["hello", "world", "python", "programming"]
uppercase_words = [word.upper() for word in words if len(word) > 5]
print(uppercase_words)  # Output: ['PYTHON', 'PROGRAMMING']

Common List Patterns #

Finding Maximum and Minimum #

numbers = [3, 1, 4, 1, 5, 9, 2]
print(max(numbers))  # Output: 9
print(min(numbers))  # Output: 1

Sum and Average #

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
average = total / len(numbers)
print(f"Sum: {total}, Average: {average}")  # Output: Sum: 15, Average: 3.0

Filtering Lists #

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Nested Lists #

Lists can contain other lists:

# 2D list (matrix)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2])  # Output: 6

# Adding to nested lists
matrix[0].append(10)
print(matrix)  # Output: [[1, 2, 3, 10], [4, 5, 6], [7, 8, 9]]

Common Mistakes and Best Practices #

1. Modifying List While Iterating #

# Wrong - can cause issues
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # Don't do this!

# Correct - iterate over a copy
numbers = [1, 2, 3, 4, 5]
for num in numbers[:]:  # numbers[:] creates a copy
    if num % 2 == 0:
        numbers.remove(num)

2. List Copying #

# Shallow copy
original = [1, 2, 3]
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)

# All create independent copies
copy1.append(4)
print(original)  # Output: [1, 2, 3]
print(copy1)     # Output: [1, 2, 3, 4]

Practical Examples #

Example 1: Grade Calculator #

def calculate_grade_stats(grades):
    if not grades:
        return "No grades provided"
    
    average = sum(grades) / len(grades)
    highest = max(grades)
    lowest = min(grades)
    
    return {
        "average": round(average, 2),
        "highest": highest,
        "lowest": lowest,
        "total_students": len(grades)
    }

# Usage
student_grades = [85, 92, 78, 96, 87, 91, 89]
stats = calculate_grade_stats(student_grades)
print(stats)

Example 2: Shopping Cart #

class ShoppingCart:
    def __init__(self):
        self.items = []
    
    def add_item(self, item, price):
        self.items.append({"item": item, "price": price})
    
    def remove_item(self, item):
        self.items = [i for i in self.items if i["item"] != item]
    
    def get_total(self):
        return sum(item["price"] for item in self.items)
    
    def get_items(self):
        return [item["item"] for item in self.items]

# Usage
cart = ShoppingCart()
cart.add_item("Apple", 1.50)
cart.add_item("Banana", 0.75)
cart.add_item("Orange", 2.00)

print(f"Items: {cart.get_items()}")
print(f"Total: ${cart.get_total():.2f}")

Practice Exercises #

  1. List Manipulation: Create a list of numbers and perform various operations (add, remove, sort, find max/min).
  2. Text Analysis: Given a list of words, find the longest word, count words with more than 5 letters, and create a new list with all words in uppercase.
  3. Data Filtering: From a list of mixed data types, separate numbers, strings, and booleans into different lists.

Summary #

In this tutorial, we covered:

  • Creating lists and accessing elements
  • Modifying lists with various methods
  • List operations and membership testing
  • List comprehensions for concise code
  • Working with nested lists
  • Common patterns and best practices
  • Practical examples and exercises

Lists are fundamental to Python programming and mastering them will greatly improve your ability to work with data and create efficient programs. Practice with the examples and try creating your own list-based projects!

Next Steps #

Now that you understand lists, explore:

  • Dictionaries: Key-value pair data structures
  • Tuples: Immutable sequences
  • Sets: Unordered collections of unique elements
  • Advanced list operations: Sorting with custom keys, functional programming with lists