Data-Structures Lecture
Data-Structures Lecture
Handling
Fundamentals and Advanced Topics
•Overview: Python provides a variety of data structures to handle collections
of data effectively. Each structure is designed to handle data differently
depending on the need.
•Key Points:
• Use Cases:
• Storing sequences of items like a collection of user inputs or a sequence of numerical data.
• Managing data that requires ordering or indexing, such as items in a to-do list or elements in a
shopping cart.
# Append an item
numbers.append(9)
print(numbers) # Output: [1, 3, 5, 7, 9]
# Insert at index 2
numbers.insert(2, 4)
print(numbers) # Output: [1, 3, 4, 5, 7, 9, 11, 13]
# Remove the first occurrence of 5
numbers.remove(5)
print(numbers) # Output: [1, 3, 4, 7, 9, 11, 13]
# Create a tuple
colors = ("red", "blue", "green", "blue")
Use Cases:
• Checking for unique values, like eliminating duplicates from a list.
• Fast membership testing, such as checking if an item exists in a set of values.
• Performing mathematical set operations, such as finding common or unique items between datasets.
Operations:
Adding elements: add()
Removing elements: discard(), remove()
Set operations: Union (|), intersection (&), difference (-)
# Intersection of sets
berries = {"strawberry", "blueberry", "cherry"}
common_fruits = fruits.intersection(berries)
print(common_fruits) # Output: {'cherry'}
List Comprehensions
Purpose:
List comprehensions provide a concise way to create lists based on existing lists or other
iterables. They are useful for applying transformations or filtering items in a clear and
efficient manner.
Use Cases:
• Transforming data, like creating a list of squares from an existing list of numbers.
• Filtering items based on conditions, such as selecting even numbers from a list
Code Example:
# List comprehension for transforming data
squares = [x ** 2 for x in range(10)] # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Code Examples:
# Basic string manipulations
message = "Hello, World!"
# Case conversions
uppercase_message = message.upper() # Output: "HELLO, WORLD!"
Code Examples:
# Nested dictionaries to store complex data
company = {
"employees": {
"Alice": {"age": 30, "position": "Developer"},
"Bob": {"age": 45, "position": "Manager"}
}
}
Code Examples:
# Writing to a file
with open("sample.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Writing multiple lines to a file.\n")
# Appending to a file
with open("sample.txt", "a") as file:
file.write("Appending a new line to the file.\n")