Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Data-Structures Lecture

This is a lecture for Data Structures.

Uploaded by

saminadeem2404
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Data-Structures Lecture

This is a lecture for Data Structures.

Uploaded by

saminadeem2404
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Python Data Structures and File

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:

◦Lists: Ordered, mutable, used for storing a collection of items.

◦Tuples: Ordered, immutable, ideal for data that shouldn’t change.

◦Dictionaries: Stores data as key-value pairs, allowing fast lookups.

◦Sets: Unordered collection of unique items, useful for membership tests.


Lists in Python
• Purpose: Lists are used to store an ordered collection of items, which are mutable and can be updated as
needed. Lists are ideal when you need to keep items in a specific order and need the ability to modify
them.

• 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.

Common List Functions:

append(): Adds a single item to the end of the list.


extend(): Adds all elements of an list (e.g., another list) to the end.
insert(): Inserts an item at a specified position.
remove(): Removes the first occurrence of a specified item.
pop(): Removes and returns the item at the specified index. Defaults to the last item if index isn’t
provided.
sort(): Sorts the list in place.
reverse(): Reverses the order of elements in place.
# Create a list of numbers
numbers = [1, 3, 5, 7]

# Append an item
numbers.append(9)
print(numbers) # Output: [1, 3, 5, 7, 9]

# Extend the list with another list


numbers.extend([11, 13])
print(numbers) # Output: [1, 3, 5, 7, 9, 11, 13]

# 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]

# Pop the last item and print it


last_item = numbers.pop()
print(last_item) # Output: 13

# Sort the list in ascending order


numbers.sort()
print(numbers) # Output: [1, 3, 4, 7, 9, 11]

# Reverse the list


numbers.reverse()
print(numbers) # Output: [11, 9, 7, 4, 3, 1]
Tuples in Python
Definition:
• Tuples are ordered and immutable collections. Once created, their elements cannot be modified.
Syntax: Tuples are defined using parentheses ().
Use Cases:
• Since tuples are immutable, they’re often used for fixed data like coordinates, where data integrity is
crucial.
Common Tuple Functions :
• count(): Returns the number of occurrences of a specified item.
• index(): Returns the index of the first occurrence of a specified item

# Create a tuple
colors = ("red", "blue", "green", "blue")

# Count occurrences of "blue"


blue_count = colors.count("blue")
print(blue_count) # Output: 2

# Find the index of the first occurrence of "green"


green_index = colors.index("green")
print(green_index) # Output: 2
Dictionaries in Python
Purpose:
• Dictionaries store data as key-value pairs, making them ideal for situations where each value
needs a unique identifier or label. They allow for fast retrieval based on keys and are
particularly useful for organizing structured data.
Use Cases:
• Storing user information with unique identifiers, like a dictionary mapping usernames to
profiles.
• Representing data mappings, such as counting occurrences with keys representing each
unique item and values representing counts.

Common Dictionary Functions and Examples:


get(): Returns the value for a specified key. If the key doesn’t exist, returns None (or a
default value).
keys(): Returns a view object of the dictionary’s keys.
values(): Returns a view object of the dictionary’s values.
items(): Returns a view object of the dictionary’s key-value pairs.
update(): Updates the dictionary with items from another dictionary.
pop(): Removes the item with the specified key and returns its value.
clear(): Removes all items from the dictionary.
# Create a dictionary
student_grades = {"Alice": 85, "Bob": 90, "Charlie": 88}

# Get a value with get()


grade = student_grades.get("Alice")
print(grade) # Output: 85

# Get keys and values


keys = student_grades.keys()
values = student_grades.values()
print(keys) # Output: dict_keys(['Alice', 'Bob', 'Charlie'])
print(values) # Output: dict_values([85, 90, 88])

# Update dictionary with new values


student_grades.update({"Alice": 95, "David": 92})
print(student_grades) # Output: {'Alice': 95, 'Bob': 90, 'Charlie': 88, 'David': 92}

# Remove and return a value using pop()


removed_grade = student_grades.pop("Bob")
print(removed_grade) # Output: 90

# Clear all items from dictionary


student_grades.clear()
print(student_grades) # Output: {}
Sets in Python
Definition: Sets are collections of unique, unordered elements, ideal for checking membership and
eliminating duplicates.
Syntax: Defined using curly braces ({}) or the set() function.

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 (-)

Common Set Functions:


add(): Adds an element to the set.
discard(): Removes a specified element if present.
pop(): Removes and returns an arbitrary element.
union(): Returns a new set containing elements from both sets.
intersection(): Returns a new set with elements common to both sets.
difference(): Returns a new set with elements in the first set but not in the second.
# Create a set
fruits = {"apple", "banana", "cherry"}

# Add an item to the set


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

# Remove an item if it exists


fruits.discard("banana")
print(fruits) # Output: {'orange', 'apple', 'cherry'}

# Union of two sets


tropical_fruits = {"mango", "pineapple"}
all_fruits = fruits.union(tropical_fruits)
print(all_fruits) # Output: {'orange', 'apple', 'cherry', 'mango', 'pineapple'}

# 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]

# Filtering items with list comprehension


even_numbers = [x for x in range(10) if x % 2 == 0] # Output: [0, 2, 4, 6, 8]
String Manipulation
Purpose:
Strings are immutable sequences of characters used to store and manipulate text. Python provides a
variety of methods for modifying and processing strings.
Use Cases:
• Formatting user input and displaying output in a specific way.
• Parsing and cleaning data in text-based formats, such as log files or user comments.
• Common String Methods and Examples.

Code Examples:
# Basic string manipulations
message = "Hello, World!"

# Case conversions
uppercase_message = message.upper() # Output: "HELLO, WORLD!"

# Replacing and splitting


replaced_message = message.replace("World", "Python") # Output: "Hello, Python!"
words = message.split(", ") # Output: ['Hello', 'World!']

# Slicing and reversing


reversed_message = message[::-1] # Output: "!dlroW ,olleH"
Advanced Data Structures - Nested Structures
Purpose:
Nested structures, such as lists of dictionaries or dictionaries within dictionaries, are useful for organizing
complex, hierarchical data.
Use Cases:
• Storing multi-level data like a database of customers, each with multiple attributes and purchase history.
• Representing data in a format that mirrors complex JSON-like structures.

Code Examples:
# Nested dictionaries to store complex data
company = {
"employees": {
"Alice": {"age": 30, "position": "Developer"},
"Bob": {"age": 45, "position": "Manager"}
}
}

# Accessing nested data


alice_position = company["employees"]["Alice"]["position"] # Output: "Developer"

# Modifying nested data


company["employees"]["Bob"]["age"] = 46
File Handling
Purpose:
Files are used to store data permanently on disk, making it possible to save program output and load it in future sessions.
Python’s built-in functions enable reading from and writing to text and binary files.
Use Cases:
• Logging program activity or errors to a file for later analysis.
• Reading and writing data to files for persistence, such as saving user preferences or loading configuration settings.

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")

# Reading from a file


with open("sample.txt", "r") as file:
content = file.read()
print(content) # Outputs the content of "sample.txt"

# Appending to a file
with open("sample.txt", "a") as file:
file.write("Appending a new line to the file.\n")

You might also like