Data Structures - Lists and Tuples
Learn how to store collections of data using Python's most versatile data structures
Learning Objectives
- Create and manipulate Python lists
- Understand list indexing and slicing
- Use common list methods (append, remove, sort)
- Understand the difference between lists and tuples
- Learn when to use immutable tuples
Collections of Data
Up until now, we’ve stored single values in variables. But in the real world, we often deal with collections: a list of users, a series of temperatures, or a shopping cart.
Python provides several built-in Data Structures to handle collections. Today we’ll cover the two most common ones: Lists and Tuples.
Python Lists
A List is an ordered, changeable collection of items. In Python, lists are written with square brackets [].
|
|
Indexing and Slicing
Items in a list are indexed starting from 0.
|
|
Modifying Lists
Lists are mutable, meaning you can change them after they are created.
|
|
Python Tuples
A Tuple is similar to a list, but it is immutable—it cannot be changed after creation. Tuples are written with parentheses ().
|
|
Why use Tuples?
- Safety: Use them for data that should never change (like GPS coordinates).
- Performance: Tuples are slightly faster than lists.
- Dictionary Keys: Tuples can be used as keys in dictionaries (which we’ll learn tomorrow).
Interactive Practice
Try creating a list of your top 3 favorite movies, then add a 4th one to the list.
| Feature | List [] |
Tuple () |
|---|---|---|
| Ordered | Yes | Yes |
| Mutable | Yes | No |
| Duplicates | Yes | Yes |
| Typical Use | Collection of items | Fixed data points |
Quiz
Complete this quiz with a minimum score of 80% to mark Day 6 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!