Python for Beginners - Part 3: Data Structures - Organizing Your Data


Welcome back to our Python coding course! In Part 2, we mastered control flow, allowing our programs to make decisions and loop through code. Now, in Part 3, we'll dive into Data Structures. These are fundamental ways to store and organize collections of data, making your programs more powerful and efficient.

Python offers several built-in data structures: Lists, Tuples, Dictionaries, and Sets.

1. Lists

Lists are ordered, changeable (mutable) collections that allow duplicate members. They are written with square brackets [].

Creating a List

# Empty list
my_list = []

# List with mixed data types
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = ["hello", 123, True, 3.14]

print(f"Fruits: {fruits}")
print(f"Numbers: {numbers}")

Accessing List Items (Indexing)

List items are indexed, starting from 0 for the first item. Negative indexing means starting from the end, where -1 is the last item.

fruits = ["apple", "banana", "cherry", "orange", "kiwi"]

print(f"First fruit: {fruits[0]}")      # Output: apple
print(f"Third fruit: {fruits[2]}")      # Output: cherry
print(f"Last fruit: {fruits[-1]}")      # Output: kiwi
print(f"Second to last: {fruits[-2]}")  # Output: orange

# Slicing: Get a range of items
print(f"Fruits from index 1 to 3 (exclusive): {fruits[1:4]}") # Output: ['banana', 'cherry', 'orange']
print(f"Fruits from start to index 2 (exclusive): {fruits[:2]}") # Output: ['apple', 'banana']
print(f"Fruits from index 2 to end: {fruits[2:]}") # Output: ['cherry', 'orange', 'kiwi']

Modifying List Items

Since lists are mutable, you can change their items after creation.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blackberry" # Change 'banana' to 'blackberry'
print(f"Modified fruits: {fruits}") # Output: ['apple', 'blackberry', 'cherry']

Common List Methods

  • append(): Adds an item to the end of the list.

  • insert(): Adds an item at a specified index.

  • remove(): Removes the first occurrence of a specified item.

  • pop(): Removes the item at a specified index (or the last item if no index is given).

  • del: Keyword to delete items by index or slice, or delete the entire list.

  • clear(): Removes all items from the list.

  • sort(): Sorts the list alphabetically or numerically.

  • reverse(): Reverses the order of the list.

  • len(): (Not a method, but a built-in function) Returns the number of items in a list.

my_list = ["a", "b", "c"]
my_list.append("d")
print(f"After append: {my_list}") # Output: ['a', 'b', 'c', 'd']

my_list.insert(1, "x")
print(f"After insert: {my_list}") # Output: ['a', 'x', 'b', 'c', 'd']

my_list.remove("b")
print(f"After remove: {my_list}") # Output: ['a', 'x', 'c', 'd']

popped_item = my_list.pop(0) # Pop item at index 0 ('a')
print(f"Popped item: {popped_item}, List now: {my_list}") # Output: Popped item: a, List now: ['x', 'c', 'd']

del my_list[1] # Delete item at index 1 ('c')
print(f"After del: {my_list}") # Output: ['x', 'd']

numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(f"Sorted numbers: {numbers}") # Output: [1, 1, 3, 4, 5, 9]

numbers.reverse()
print(f"Reversed numbers: {numbers}") # Output: [9, 5, 4, 3, 1, 1]

print(f"Length of numbers: {len(numbers)}") # Output: 6

2. Tuples

Tuples are ordered, unchangeable (immutable) collections that allow duplicate members. They are written with round brackets (). Once a tuple is created, you cannot change, add, or remove items.

my_tuple = ("apple", "banana", "cherry")
print(f"My tuple: {my_tuple}")

# Accessing tuple items (same as lists)
print(f"First item: {my_tuple[0]}")

# You cannot modify a tuple:
# my_tuple[1] = "blackberry" # This would raise an error!

Tuples are often used for fixed collections of items or when returning multiple values from a function.

3. Dictionaries

Dictionaries are unordered (in older Python versions, ordered from Python 3.7+), changeable, and indexed collections. They store data in key-value pairs. Keys must be unique and immutable (like strings, numbers, or tuples), while values can be of any data type. Dictionaries are written with curly brackets {}.

Creating a Dictionary

person = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

print(f"Person dictionary: {person}")

Accessing Dictionary Items

You can access items by referring to their key inside square brackets [] or by using the get() method.

print(f"Person's name: {person['name']}")   # Output: John Doe
print(f"Person's age: {person.get('age')}") # Output: 30

Modifying Dictionary Items

You can change the value of a specific item by referring to its key. Adding new items is done by assigning a value to a new key.

person["age"] = 31 # Change age
person["occupation"] = "Engineer" # Add new key-value pair

print(f"Updated person: {person}")

Removing Dictionary Items

  • pop(): Removes the item with the specified key.

  • popitem(): Removes the last inserted item (before Python 3.7, it removed a random item).

  • del: Keyword to delete an item with a specified key or delete the dictionary entirely.

  • clear(): Empties the dictionary.

car = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}

car.pop("model")
print(f"After pop('model'): {car}") # Output: {'brand': 'Ford', 'year': 1964}

del car["year"]
print(f"After del 'year': {car}") # Output: {'brand': 'Ford'}

# car.clear() # Empties the dictionary
# del car     # Deletes the dictionary entirely

4. Sets

Sets are unordered, unchangeable (you cannot change items after creation, but you can add/remove items), and unindexed collections. They do not allow duplicate members. Sets are written with curly brackets {}.

Creating a Set

my_set = {"apple", "banana", "cherry"}
print(f"My set: {my_set}")

# Sets automatically remove duplicates
numbers_set = {1, 2, 3, 2, 1, 4}
print(f"Numbers set (duplicates removed): {numbers_set}") # Output: {1, 2, 3, 4} (order might vary)

Adding and Removing Items

  • add(): Adds a single item.

  • update(): Adds multiple items from another iterable (list, tuple, etc.).

  • remove(): Removes a specified item. Raises an error if the item is not found.

  • discard(): Removes a specified item. Does NOT raise an error if the item is not found.

fruits_set = {"apple", "banana", "cherry"}
fruits_set.add("orange")
print(f"After add: {fruits_set}")

fruits_set.update(["grape", "kiwi"])
print(f"After update: {fruits_set}")

fruits_set.remove("banana")
print(f"After remove: {fruits_set}")

fruits_set.discard("mango") # Mango is not in the set, no error
print(f"After discard (no mango): {fruits_set}")

Set Operations

Sets support mathematical set operations like union, intersection, difference.

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

# Union: all unique items from both sets
union_set = set1.union(set2)
print(f"Union: {union_set}") # Output: {1, 2, 3, 4, 5, 6}

# Intersection: items present in both sets
intersection_set = set1.intersection(set2)
print(f"Intersection: {intersection_set}") # Output: {3, 4}

# Difference: items in set1 but not in set2
difference_set = set1.difference(set2)
print(f"Difference (set1 - set2): {difference_set}") # Output: {1, 2}

Summary of Part 3

You've now explored the core built-in Python data structures:

  • Lists: Ordered, mutable, allows duplicates (use for collections that change).

  • Tuples: Ordered, immutable, allows duplicates (use for fixed collections).

  • Dictionaries: Key-value pairs, mutable, unique keys (use for mapping data).

  • Sets: Unordered, mutable (for adding/removing), no duplicates (use for unique collections and set operations).

Understanding these structures is crucial for handling and manipulating data effectively in Python. In the final part, Part 4, we'll learn about Functions and Modules, which will help you organize your code into reusable blocks and leverage existing Python functionalities!

Comments

Popular posts from this blog

Python for Beginners - Part 4: Functions and Modules - Organizing and Reusing Code

Python for Beginners - Part 1: Getting Started with Python Basics

Safe use of internet