Topic Overview and Introduction

Hello! Today, we're investigating Python data structures: lists, tuples, sets, and dictionaries. These structures represent different ways of organizing data in Python, each with unique properties, making them useful for diverse needs. For instance, you can use lists to maintain a to-do list, tuples to store geographical coordinates (as these values are paired and don't tend to change), sets to keep track of all unique students in a class, and dictionaries to represent user profile data in key-value pairs!

In this lesson, we will explore these properties using practical examples. This understanding is crucial in many real-world scenarios, where choosing the right structure can significantly enhance the performance and efficiency of your code.

Peeling Back the Layers of Python Data Structures: Properties Revisited

In Python, the tools we use to store and handle data are termed data structures. Lists and tuples are similar, as they are ordered collections of items. In contrast, sets are unordered collections of unique items, and dictionaries store data in key-value pairs.

my_list = ["apple", "banana", "cherry"] # An ordered list of fruits
my_tuple = ("apple", "banana", "cherry") # An ordered, immutable tuple of fruits
my_set = {"apple", "banana", "cherry"} # A set of unique fruits
my_dict = {"name" : "apple", "color" : "red", "type" : "fruit"} # A dictionary representing a fruit
Lists vs. Tuples: More than Just Mutability

Lists and Tuples can store multiple items, and we can access these items with indexes. Lists are mutable, meaning we can alter their content, but tuples are not. Additionally, tuples use less memory than lists, making them an efficient choice when you're dealing with a collection of items that don't need to be altered.

my_list = ["apple", "banana", "cherry"]
my_list[1] = "blueberry" # We can change list elements

my_tuple = ("apple", "banana", "cherry")
try:
    my_tuple[1] = "blueberry" # Trying to change a tuple raises an error
except TypeError:
    print("Cannot modify a tuple!")
Lists & Tuples vs. Sets: The Power of Uniqueness & Order

While lists and tuples maintain the order of items, sets do not, but they store only unique items. Hence, when order matters, like arranging tasks for the day, we use lists or tuples. When we need to gather unique items, like a class attendance list, sets are a preferable choice.

fruit_list = ["apple", "banana", "cherry", "apple", "banana"] # List retains order and duplicates
fruit_tuple = ("apple", "banana", "cherry", "apple", "banana") # Same as a list, but immutable

fruit_set = {"apple", "banana", "cherry", "apple", "banana"} # Sets do not retain order, and remove duplicates
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal