Table of contents

Data Structures

Data structures are essential tools for organizing and managing data efficiently in your programs. Python provides several built-in data structures, including lists, tuples, dictionaries, and sets. This comprehensive guide will cover each of these data structures in detail, with examples to help you understand their usage and capabilities.

Lists are ordered, mutable collections of items. They can store items of different types, and you can modify their contents after creation.

You can create lists using square brackets [] or the list() constructor.

fruits = ["apple", "banana", "cherry"] numbers = list(range(1, 6)) mixed = [1, "hello", 3.14, True]

You can access list items using their index, starting from 0.

fruits = ["apple", "banana", "cherry"] print(fruits[0]) # Output: apple print(fruits[-1]) # Output: cherry

You can change the value of list items by assigning a new value to a specific index.

fruits = ["apple", "banana", "cherry"] fruits[1] = "blueberry" print(fruits) # Output: ['apple', 'blueberry', 'cherry']

Lists have several built-in methods for adding, removing, and manipulating items.

# Adding items fruits.append("orange") fruits.insert(1, "kiwi") # Removing items fruits.remove("banana") popped_item = fruits.pop() # Removes the last item fruits.pop(1) # Removes the item at index 1 del fruits[0] # Removes the item at index 0 # Other methods fruits.sort() fruits.reverse() print(fruits.index("cherry")) print(fruits.count("apple"))

Example: List Operations

numbers = [1, 2, 3, 4, 5] # Sum of all elements total = sum(numbers) print(f"Sum: {total}") # Average of all elements average = total / len(numbers) print(f"Average: {average}") # Check if an element exists if 3 in numbers: print("3 is in the list")

Tuples are ordered, immutable collections of items. Once a tuple is created, its contents cannot be changed.

You can create tuples using parentheses () or the tuple() constructor.

coordinates = (10, 20) names = tuple(["Alice", "Bob", "Charlie"]) single_item_tuple = (42,) # Note the trailing comma

You can access tuple items using their index, starting from 0.

coordinates = (10, 20) print(coordinates[0]) # Output: 10

Tuples have fewer methods compared to lists because they are immutable.

# Counting occurrences print(names.count("Alice")) # Finding the index of an item print(names.index("Bob"))

Example: Tuple Operations

dimensions = (1920, 1080) # Unpacking tuple width, height = dimensions print(f"Width: {width}, Height: {height}") # Combining tuples tuple1 = (1, 2) tuple2 = (3, 4) combined = tuple1 + tuple2 print(combined) # Output: (1, 2, 3, 4)

Dictionaries are unordered collections of key-value pairs. They allow you to store and retrieve data efficiently using unique keys.

You can create dictionaries using curly braces {} or the dict() constructor.

student = {"name": "Alice", "age": 25, "courses": ["Math", "Science"]} empty_dict = dict()

You can access dictionary items using their keys.

print(student["name"]) # Output: Alice print(student.get("age")) # Output: 25 print(student.get("grade", "N/A")) # Output: N/A

You can add, update, or remove items in a dictionary.

# Adding/updating items student["grade"] = "A" student.update({"age": 26, "name": "Bob"}) # Removing items del student["courses"] age = student.pop("age")

Dictionaries have several built-in methods for working with their keys and values.

# Getting keys, values, and items keys = student.keys() values = student.values() items = student.items() # Iterating through dictionary for key, value in student.items(): print(key, value)

Example: Dictionary Operations

grades = {"Alice": 90, "Bob": 85, "Charlie": 92} # Average grade average_grade = sum(grades.values()) / len(grades) print(f"Average grade: {average_grade}") # Check if a student is in the dictionary if "Alice" in grades: print("Alice's grade:", grades["Alice"])

Sets are unordered collections of unique items. They are useful for membership tests and eliminating duplicates.

You can create sets using curly braces {} or the set() constructor.

fruits = {"apple", "banana", "cherry"} empty_set = set()

You can add or remove items from a set.

# Adding items fruits.add("orange") fruits.update(["kiwi", "mango"]) # Removing items fruits.remove("banana") fruits.discard("apple") # Doesn't raise an error if the item is not found popped_item = fruits.pop() # Removes and returns an arbitrary item

Sets support mathematical operations like union, intersection, difference, and symmetric difference.

set1 = {1, 2, 3} set2 = {3, 4, 5} # Union union_set = set1 | set2 # {1, 2, 3, 4, 5} # Intersection intersection_set = set1 & set2 # {3} # Difference difference_set = set1 - set2 # {1, 2} # Symmetric Difference symmetric_difference_set = set1 ^ set2 # {1, 2, 4, 5}

Example: Set Operations

students = {"Alice", "Bob", "Charlie"} graduates = {"Bob", "David"} # Students who are also graduates graduates_students = students & graduates print(graduates_students) # Output: {'Bob'} # Students who are not graduates non_graduates = students - graduates print(non_graduates) # Output: {'Alice', 'Charlie'} # All people involved all_people = students | graduates print(all_people) # Output: {'Alice', 'Bob', 'Charlie', 'David'}

Write a program to find all unique words in a sentence using a set.

sentence = "the quick brown fox jumps over the lazy dog the quick brown fox" words = sentence.split() unique_words = set(words) print(unique_words)

Write a program to manage student grades using a dictionary.

grades = {} # Adding grades grades["Alice"] = 90 grades["Bob"] = 85 # Updating grades grades["Alice"] = 95 # Removing a student del grades["Bob"] # Printing all grades for student, grade in grades.items(): print(f"{student}: {grade}")

Write a program to create a list of squares for the numbers 1 to 10 using list comprehensions.

squares = [x**2 for x in range(1, 11)] print(squares)

Write a program to combine two tuples and find the maximum value in the combined tuple.

tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) combined_tuple = tuple1 + tuple2 max_value = max(combined_tuple) print(combined_tuple) print(f"Maximum value: {max_value}")

In this guide, we’ve explored Python’s built-in data structures: lists, tuples, dictionaries, and sets. Each of these data structures has unique characteristics and use cases, making them powerful tools for organizing and managing data efficiently. Practice these concepts with the provided examples and exercises to enhance your understanding and programming skills. In the next section, we will delve into strings and string manipulation, which are essential for working with text data. Happy coding!