Python Lists, Tuples, and Dictionaries: A Beginner’s Guide

Master Python lists, tuples, and dictionaries with this beginner-friendly guide. Learn essential methods, best practices, and practical examples!
code
python
Author

Steven P. Sanderson II, MPH

Published

June 11, 2025

Keywords

Programming, Python lists, Python tuples, Python data structures, Python dictionaries, Python colections, dictionary methods Python, Python mutable vs immutable, list vs tuple Python Python list operations, Python data structure comparison, convert list to tuple in Python with examples, how to choose between list tuple and dictionary in Python, best practices for passing lists to functions in Python, Python dictionary key-value pair manipulation, when to use tuples instead of lists in Python

Author’s Note: I want to be transparent with you, I’m learning Python as I write this series. Rather than an expert tutorial, this is a series of discovery where I’m documenting concepts as I understand them, sharing insights, and yes, occasionally making mistakes along the way.

Introduction

Python offers several built-in collection types that make it easy to store, organize, and manipulate data. These collections are fundamental building blocks for nearly any Python program, and understanding their differences is essential for writing efficient code.

The three most commonly used collection types are:

  • Lists: Ordered, mutable collections that can store items of any type
  • Tuples: Ordered, immutable collections that can store items of any type
  • Dictionaries: Unordered, mutable collections of key-value pairs

As a beginner Python programmer, you’ll find yourself using lists most frequently due to their flexibility and intuitive behavior. Lists allow you to collect related items together, modify them at any time, and perform operations like adding, removing, or rearranging elements.

Creating and Accessing Lists

List Creation Syntax

Python lists are created using square brackets []. You can create an empty list or initialize one with values:

reticulate::repl_python()
Python 3.11.13 (C:/Users/ssanders/AppData/Local/R/cache/R/reticulate/uv/cache/archive-v0/KVkhPXn-Fo7Nm8piyYSN5/Scripts/python.exe)
Reticulate 1.42.0 REPL -- A Python interpreter in R.
Enter 'exit' or 'quit' to exit the REPL and return to R.
exit
# Empty list
empty_list = []
empty_list
[]
also_empty = list()  # Using the list constructor
also_empty
[]
# List with values
numbers = [1, 2, 3, 4, 5]
numbers
[1, 2, 3, 4, 5]
mixed_types = [1, "hello", 3.14, True]
mixed_types
[1, 'hello', 3.14, True]
nested_list = [1, [2, 3], 4]  # Lists can contain other lists
nested_list
[1, [2, 3], 4]

Lists in Python can hold any type of data, including numbers, strings, booleans, and even other lists. This flexibility makes them extremely versatile.

List Indexing and Slicing

Python uses zero-based indexing, meaning the first element is at position 0:

my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[0])  # Output: 'a'
a
print(my_list[3])  # Output: 'd'
d

You can also use negative indices to access elements from the end of the list:

print(my_list[-1])  # Output: 'e' (last element)
e
print(my_list[-2])  # Output: 'd' (second-to-last element)
d

Slicing allows you to extract a portion of a list using the syntax [start:stop:step]:

print(my_list[1:4])    # Output: ['b', 'c', 'd']
['b', 'c', 'd']
print(my_list[:3])     # Output: ['a', 'b', 'c']
['a', 'b', 'c']
print(my_list[2:])     # Output: ['c', 'd', 'e']
['c', 'd', 'e']
print(my_list[::2])    # Output: ['a', 'c', 'e']
['a', 'c', 'e']

Understanding List Mutability

What Makes Lists Mutable

In programming, mutability refers to whether an object can be changed after it’s created. Lists are mutable, meaning you can modify, add, or remove elements without creating a new list:

numbers = [1, 2, 3]
numbers[0] = 10        # Modify the first element
print(numbers)         # Output: [10, 2, 3]
[10, 2, 3]

This mutability is a key feature that distinguishes lists from immutable types like tuples, which cannot be changed after creation.

Variables and References

When you assign a list to a variable, Python creates a reference to the list rather than a new copy. This means multiple variables can point to the same list:

list_a = [1, 2, 3]
list_b = list_a        # list_b references the same list as list_a

list_b[0] = 10         # This changes the list that both variables reference
print(list_a)          # Output: [10, 2, 3]
[10, 2, 3]
print(list_b)          # Output: [10, 2, 3]
[10, 2, 3]

To create an independent copy, you can use:

list_c = list_a[:]     # Creates a shallow copy using slicing
list_d = list_a.copy() # Another way to create a shallow copy

print(list_c)
[10, 2, 3]
print(list_d)
[10, 2, 3]

Essential List Methods

Lists have many built-in methods that allow you to manipulate their contents efficiently. Here are the most commonly used:

Adding Elements

my_list = [1, 2, 3]
print(my_list)
[1, 2, 3]
# Add an element at the end
my_list.append(4)      # Result: [1, 2, 3, 4]
print(my_list)
[1, 2, 3, 4]
# Insert at a specific position
my_list.insert(1, 5)   # Result: [1, 5, 2, 3, 4]
print(my_list)
[1, 5, 2, 3, 4]
# Extend with elements from another iterable
my_list.extend([6, 7]) # Result: [1, 5, 2, 3, 4, 6, 7]
print(my_list)
[1, 5, 2, 3, 4, 6, 7]

Removing Elements

my_list = [1, 2, 3, 2, 4]
print(my_list)
[1, 2, 3, 2, 4]
# Remove by value (first occurrence)
my_list.remove(2)      # Result: [1, 3, 2, 4]
print(my_list)
[1, 3, 2, 4]
# Remove by index
del my_list[2]         # Result: [1, 3, 4]
print(my_list)
[1, 3, 4]
# Remove and return the element at a specific index
popped = my_list.pop(1)  # popped = 3, my_list = [1, 4]
print(popped)
3

Finding and Organizing Elements

my_list = [3, 1, 4, 1, 5, 9]
print(my_list)
[3, 1, 4, 1, 5, 9]
# Find the index of the first occurrence
position = my_list.index(4)  # Result: 2
print(position)
2
# Count occurrences
count = my_list.count(1)     # Result: 2
print(count)
2
# Reverse the list in place
my_list.reverse()            # Result: [9, 5, 1, 4, 1, 3]

# Sort the list in place
my_list.sort()               # Result: [1, 1, 3, 4, 5, 9]

# Get a sorted copy without modifying the original
sorted_list = sorted(my_list)
print(sorted_list)          # Output: [1, 1, 3, 4, 5, 9]
[1, 1, 3, 4, 5, 9]

List Iteration and Comprehensions

Iterating Through Lists

The most common way to iterate through a list is with a for loop:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
apple
banana
cherry

When you need both the index and value, use enumerate():

for index, fruit in enumerate(fruits):
    print(f"Item {index}: {fruit}")
Item 0: apple
Item 1: banana
Item 2: cherry

List Comprehensions

List comprehensions provide a concise way to create lists from existing iterables:

# Create a list of squares
squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]
print(squares)
[0, 1, 4, 9, 16]
# Filter elements 
even_squares = [x**2 for x in range(10) if x % 2 == 0]  # [0, 4, 16, 36, 64]
print(even_squares)
[0, 4, 16, 36, 64]

This syntax is often more readable and efficient than building lists with for loops.

Tuples: Immutable Ordered Collections

Creating and Using Tuples

Tuples are similar to lists but are immutable (cannot be changed after creation). They’re created using parentheses:

empty_tuple = ()
print(empty_tuple)  # Output: ()
()
single_item = (42,)    # Comma is required for single-item tuples!
print(single_item)  # Output: (42,)
(42,)
coordinates = (10, 20)
print(coordinates)  # Output: (10, 20)
(10, 20)
mixed_tuple = (1, "hello", True)
print(mixed_tuple)  # Output: (1, 'hello', True)
(1, 'hello', True)

Once created, tuple elements cannot be modified:

coordinates = (10, 20)
# coordinates[0] = 5  # This would raise a TypeError

Lists vs Tuples: A Practical Comparison

Feature Lists Tuples
Syntax [1, 2, 3] (1, 2, 3)
Mutability Mutable (can be changed) Immutable (cannot be changed)
Use Case When you need to modify items When data should remain constant
Performance Slightly slower operations Slightly faster operations
Dict Keys Cannot be used as dict keys Can be used as dict keys

Tuples are ideal for representing fixed collections like coordinates or RGB color values, while lists are better when you need to modify the content.

Dictionaries: Key-Value Collections

Dictionary Fundamentals

Dictionaries store data as key-value pairs, providing fast access to values via their keys:

# Creating a dictionary
person = {
    'name': 'Alice',
    'age': 25,
    'city': 'New York'
}

# Accessing values
print(person['name'])  # Output: 'Alice'
Alice
# Adding/modifying entries
person['email'] = '[email protected]'
person['age'] = 26

print(person['email'])
print(person['age'])  # Output: 26
26

Common Dictionary Methods

# Safe access with default value
email = person.get('email', 'Not provided')

# Get all keys, values, or items
keys = person.keys()
values = person.values()
items = person.items()

# Iterate through key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")
name: Alice
age: 26
city: New York
email: [email protected]

Interactive Exercise: Your Turn!

Let’s put your knowledge into practice by creating a simple shopping list application.

The Shopping List Challenge:

Create a program that allows you to:

  1. Add items with quantities
  2. Remove items
  3. Update quantities
  4. Display the current list

Here’s a skeleton to get you started:

# Challenge: Complete the ShoppingList class implementation
class ShoppingList:
    def __init__(self):
        self.items = {}  # Dictionary to store item:quantity pairs
        
    def add_item(self, item, quantity=1):
        # Your code here
        pass
            
    def remove_item(self, item):
        # Your code here
        pass
    
    def update_quantity(self, item, quantity):
        # Your code here
        pass
            
    def get_list(self):
        # Your code here
        pass
Click here for Solution!
class ShoppingList:
    def __init__(self):
        self.items = {}  # Dictionary to store item:quantity pairs
        
    def add_item(self, item, quantity=1):
        """Add an item to the shopping list or update its quantity."""
        item = item.lower().strip()
        if not item:
            raise ValueError("Item name cannot be empty")
        if quantity <= 0:
            raise ValueError("Quantity must be positive")
            
        if item in self.items:
            self.items[item] += quantity
        else:
            self.items[item] = quantity
            
    def remove_item(self, item):
        """Remove an item from the shopping list."""
        item = item.lower().strip()
        if item in self.items:
            del self.items[item]
            return True
        return False
    
    def update_quantity(self, item, quantity):
        """Update the quantity of an existing item."""
        item = item.lower().strip()
        if item not in self.items:
            raise KeyError(f"Item '{item}' not found in shopping list")
        if quantity <= 0:
            self.remove_item(item)
        else:
            self.items[item] = quantity
            
    def get_list(self):
        """Return the current shopping list."""
        return dict(sorted(self.items.items()))

# Example usage:
shopping = ShoppingList()
shopping.add_item("Apples", 3)
shopping.add_item("Bananas", 2)
print(shopping.get_list())  # {'apples': 3, 'bananas': 2}

Common Pitfalls and Best Practices

Reference vs Copy

One of the most common mistakes beginners make is not understanding how references work:

# WRONG (if you want independent lists)
list1 = [1, 2, 3]
list2 = list1
list2.append(4)  # Now list1 will also have 4!

# RIGHT (creating independent copies)
list1 = [1, 2, 3]
list2 = list1.copy()  # or list1[:] for a shallow copy
list2.append(4)  # list1 remains [1, 2, 3]

Choosing the Right Collection Type

  • Use lists when you need an ordered, mutable collection
  • Use tuples for fixed, immutable sequences of data
  • Use dictionaries when you need fast lookups by key

Quick Takeaways

  • Lists are mutable, ordered collections created with []
  • Append adds elements to the end with .append(item)
  • Remove elements by value with .remove(value) or by index with del list[index]
  • Reverse a list in place with .reverse()
  • Index finds an element’s position with .index(value)
  • Use list comprehensions [expression for item in iterable] for concise, readable code
  • Tuples are immutable lists, good for data that shouldn’t change
  • Dictionaries store key-value pairs for fast lookups

Conclusion and Next Steps

You now have a solid foundation in Python’s core collection types, particularly lists. Practice using these structures in your own programs to reinforce your understanding. As you advance, explore more specialized collections in the collections module like Counter, defaultdict, and namedtuple for more specific use cases.

FAQ Section

Q: Can lists contain different types of data?
A: Yes, Python lists can contain mixed data types, including other lists.

Q: When should I use a list vs. a tuple?
A: Use lists when you need to modify the collection and tuples when the data should remain constant.

Q: Are dictionaries ordered in Python?
A: Since Python 3.7, dictionaries maintain insertion order, but they’re still optimized for lookups by key, not by position.

Q: How do I sort a list in reverse order?
A: Use my_list.sort(reverse=True) or sorted(my_list, reverse=True).

Q: Can I have duplicate values in a list?
A: Yes, lists can contain duplicate values, unlike sets which only store unique elements.

References

  1. Python Software Foundation. (2025). Python 3.11 Documentation: Data Structures. Access Documentation > Comprehensive guide to Python’s built-in data structures including lists, tuples, and dictionaries with official syntax and usage examples.

  2. Python Software Foundation. (2025). Python 3.11 Documentation: Sequence Types. Access Documentation > Detailed reference for sequence types including lists and tuples with all available methods and operations.

  3. Python Software Foundation. (2025). Python 3.11 Documentation: Mapping Types. Access Documentation > Complete reference for dictionary operations, methods, and examples of common usage patterns.


I hope this guide helps you understand and use Python’s collection types effectively. Remember that practice is key to mastering these concepts. Try building small projects that use different collection types to reinforce your learning.


Happy Coding! 🚀

Lists in Python

You can connect with me at any one of the below:

Telegram Channel here: https://t.me/steveondata

LinkedIn Network here: https://www.linkedin.com/in/spsanderson/

Mastadon Social here: https://mstdn.social/@stevensanderson

RStats Network here: https://rstats.me/@spsanderson

GitHub Network here: https://github.com/spsanderson

Bluesky Network here: https://bsky.app/profile/spsanderson.com

My Book: Extending Excel with Python and R here: https://packt.link/oTyZJ

You.com Referral Link: https://you.com/join/EHSLDTL6