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

0

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

Python provides powerful built-in data structures for efficient data storage and manipulation. In this guide, you’ll learn how to use lists, tuples, sets, and dictionaries with detailed explanations, practical examples, and hands-on exercises.

Lists

Lists are ordered, mutable collections of items. They are ideal for storing sequences of data where the order matters, and you may need to modify the data later.

Creating Lists

servers = ['web1', 'web2', 'db1']

Lists are created using square brackets []. Items are separated by commas.

Accessing Elements

first_server = servers[0]  # 'web1'

You can access elements using their index. Python uses zero-based indexing, so the first element is at index 0.

Modifying Lists

Lists are mutable, meaning you can change their content after creation.

servers.append('cache1')  # Add item to the end
servers.remove('db1')     # Remove item by value
web_servers = servers[:2] # Slice to get the first two items

Common operations include adding, removing, and slicing elements.

Common List Methods

  • append(): Add an item to the end.
  • remove(): Remove an item by value.
  • sort(): Sort the list in place.
  • reverse(): Reverse the list in place.
  • insert(): Insert an item at a specific index.

Tuples

Tuples are ordered, immutable collections. Once created, their content cannot be changed. They are ideal for storing fixed data, such as configuration settings.

Creating Tuples

config = ('localhost', 8080)

Tuples are created using parentheses (). Items are separated by commas.

Accessing Elements

host = config[0]  # 'localhost'

Like lists, you can access tuple elements using their index.

Immutability

# config[0] = '127.0.0.1'  # Error: Tuples are immutable

Once a tuple is created, you cannot modify its elements. This makes tuples safer for storing data that should not change.

Sets

Sets are unordered collections of unique elements. They are useful for eliminating duplicates and performing mathematical set operations like union, intersection, and difference.

Creating Sets

unique_users = {'alice', 'bob', 'charlie'}

Sets are created using curly braces {}. Items are separated by commas.

Adding Elements

unique_users.add('david')

You can add elements to a set using the add() method.

Set Operations

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

# Union: Combine elements from both sets
all_users = set1.union(set2)  # {1, 2, 3, 4, 5}

# Intersection: Find common elements
common_users = set1.intersection(set2)  # {3}

# Difference: Find elements in set1 but not in set2
diff_users = set1.difference(set2)  # {1, 2}

Sets are powerful for comparing and combining collections of data.

Dictionaries

Dictionaries store key-value pairs. They are ideal for mapping relationships between data, such as user roles or product prices.

Creating Dictionaries

user_roles = {'alice': 'admin', 'bob': 'user'}

Dictionaries are created using curly braces {} with key-value pairs separated by commas.

Accessing Values

role = user_roles['alice']  # 'admin'

You can access values using their keys. If the key does not exist, Python raises a KeyError.

Adding/Modifying Entries

user_roles['charlie'] = 'moderator'

You can add or modify dictionary entries by assigning a value to a key.

Practice Work

Exercise 1: List Manipulation

Create a list of fruits and perform the following:

  1. Add “banana”.
  2. Remove “apple”.
  3. Print the first two fruits.
fruits = ['apple', 'orange', 'grape']
Solution:

fruits.append('banana')
fruits.remove('apple')
print(fruits[:2])

Exercise 2: Tuple Unpacking

Unpack the following tuple into variables:

coordinates = (10.5, 20.3)
Solution:

x, y = coordinates

Exercise 3: Set Operations

Given two sets, find the union, intersection, and difference:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
Solution:

union = set1.union(set2)
intersection = set1.intersection(set2)
difference = set1.difference(set2)

Exercise 4: Dictionary Lookup

Add a new user to the dictionary and print their role:

user_roles = {'alice': 'admin', 'bob': 'user'}
Solution:

user_roles['charlie'] = 'moderator'
print(user_roles['charlie'])

Workshop: Real-World Applications

Workshop 1: Inventory Management

Use a dictionary to track product stock levels:

inventory = {'apples': 50, 'bananas': 30, 'oranges': 40}
# Add 10 more apples
# Remove bananas
# Print the updated inventory

Workshop 2: Unique Usernames

Use a set to store unique usernames and prevent duplicates:

usernames = {'alice', 'bob'}
# Add 'charlie' and 'alice'
# Print the set

Best Practices

  • Use Lists for Ordered Data: When order matters.
  • Use Tuples for Immutable Data: When data should not change.
  • Use Sets for Unique Items: When duplicates are not allowed.
  • Use Dictionaries for Key-Value Pairs: When mapping relationships.

Conclusion

Mastering Python’s core data structures—lists, tuples, sets, and dictionaries—will help you store and manipulate data efficiently. Practice the exercises and workshops to solidify your understanding.

Next Steps: Explore Python List Comprehensions or Python Functions.

 

Choose your Reaction!
Leave a Comment

Your email address will not be published.