Python Data Structures: Lists, Tuples, Sets, and Dictionaries

Python Data Structures: Lists, Tuples, Sets, and Dictionaries

Introduction

Data structures are used to organize and store data in a particular way, making it efficient to access, manipulate, and manage the data. Python provides a rich set of data structures that allow developers to efficiently store and manipulate data.

Python data structures can be classified into two: Mutable and Immutable. Mutable data structures are ones in which the current values of the data types can be modified i.e. those that can have their elements changed, added, or removed. Lists, dictionaries, and sets are the three mutable data structures available in Python.

On the other hand, immutable data structures in which the current values of the data types cannot be modified after they are created. Tuples are the only immutable data structure in Python.

Three fundamental data structures in Python are lists, tuples, sets, and dictionaries. In this article, we will delve into each of these data structures, exploring their characteristics, use cases and common operations.

Objectives

At the end of this tutorial, you will:

  • Understand the purpose and characteristics of different data structures in Python.

  • Learn how to create and manipulate data structures.

  • Explore the operations and methods available for each data structure.

Lists

Lists are versatile and mutable sequences that can hold elements of different data types. List items are ordered and indexed i.e. they can have items with identical values. They are defined using square brackets [] and support indexing and slicing.

Example:

# Creating a list
fruits = ['apple', 'banana', 'cherry', 'date']

# Number of items in the list:
print(len(fruits)) #Output: 4

# Accessing elements
# The first item has index 0.
print(fruits[0])  # Output: 'apple'
print(fruits[1:3])  # Output: ['banana', 'cherry']

# Modifying elements
fruits[0] = 'avocado'
print(fruits)  # Output: ['avocado', 'banana', 'cherry', 'date']

# Adding elements
fruits.append('elderberry')
print(fruits)  # Output: ['avocado', 'banana', 'cherry', 'date', 'elderberry']

# Removing elements
fruits.remove('banana')
print(fruits)  # Output: ['avocado', 'cherry', 'date', 'elderberry']

Tuples

Tuples are immutable sequences enclosed in parentheses (). Unlike lists, tuples cannot be modified once created. They are ordered and indexed i.e. they can have items with identical values. They are often used to represent fixed collections of related values.

Example:

# Creating a tuple
person = ('John', 25, 'USA')

# Number of items in the Tuple:
print(len(person)) #Output: 3

# Accessing elements
print(person[0])  # Output: 'John'
print(person[1:])  # Output: (25, 'USA')

# Unpacking tuples
name, age, country = person
print(name, age, country)  # Output: 'John', 25, 'USA'

# Error: Tuples are immutable, so modification is not allowed
person[1] = 26

# Change the values of tuple
# Convert the tuple into a list
person_list = list(person)
person_list[1] = 20
# Convert the list back to a tuple
person = tuple(person_list)
print(person) # Output: ('John', 20, 'USA')

# Removing elements
# Convert the tuple into a list
person_list = list(person)
person_list.remove('John')
# Convert the list back to a tuple
person = tuple(person_list)
print(person) # Output: (20, 'USA')

Dictionaries

Dictionaries are key-value pairs enclosed in curly braces {}. They provide fast access to values based on unique keys. Dictionaries are unordered, and mutable, and allow storing of elements of different types.

Example:

# Creating a dictionary
student = {'name': 'Alice', 'age': 20, 'major': 'Computer Science'}

# Accessing values
print(student['name'])  # Output: 'Alice'
print(student.get('age'))  # Output: 20

# Modifying values
student['age'] = 21
print(student)  # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

# Adding new key-value pairs
student['university'] = 'ABC University'
print(student)  # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science', 'university': 'ABC University'}

# Removing key-value pairs
del student['major']
print(student)  # Output: {'name': 'Alice', 'age': 21, 'university': 'ABC University'}

Sets

Sets are a built-in data structure that represents an unordered collection of unique elements. Sets are useful when you want to store a collection of items without any duplicates.

Example:

# Creating an empty set
empty_set = set()
print(empty_set)  # Output: set()

# Creating a set with elements
fruits = {'apple', 'banana', 'orange'}
print(fruits)  # Output: {'orange', 'apple', 'banana'}

# Creating a set from a list
numbers = set([1, 2, 3, 4, 5])
print(numbers)  # Output: {1, 2, 3, 4, 5}

# Adding elements
fruits.add('orange')
print(fruits)  # Output: {'apple', 'banana', 'orange'}

# Removing elements
fruits = {'apple', 'banana', 'orange'}
fruits.remove('banana')
print(fruits)  # Output: {'apple', 'orange'}

fruits.discard('mango')  # No error raised
print(fruits)  # Output: {'apple', 'orange'}

Basic Sets Operations

Sets provide operations like union, intersection, difference, and symmetric difference.

set1 = {1, 2, 3}
set2 = {2, 3, 4}

# Union of sets
union_set = set1.union(set2)
print(union_set)  # Output: {1, 2, 3, 4}

# Intersection of sets
intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {2, 3}

# Difference of sets
difference_set = set1.difference(set2)
print(difference_set)  # Output: {1}

# Symmetric difference of sets
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)  # Output: {1, 4}

Conclusion

Understanding and effectively utilizing Python's data structures is crucial for efficient programming.

In this tutorial, we explored lists, tuples, and dictionaries. Lists offer flexibility with mutable sequences, tuples provide immutability for fixed collections, and dictionaries enable efficient key-value pair storage. By mastering these data structures, you can enhance your Python programming skills and build powerful applications.

Thanks for reading!