Python Data Structures Unit1-1
Python Data Structures Unit1-1
Structures
Unit 1
Key differences
Allows
Data Structure Ordered? Mutable? Indexed?
Duplicates?
✅ Yes (Python
Dictionary ✅ Yes ❌ No (keys) ❌ No
3.6+)
Set ❌ No ✅ Yes ❌ No ❌ No
A list is a mutable
(modifiable) ordered
collection of elements.
Characteristics of Lists
List
• Ordered (elements have a specific
order)
• Mutable (can be changed)
• Can store different data types
• Supports indexing and slicing
Example
• # Creating a list
my_list = [10, "Python", 3.14, True]
• # Empty list
empty_list = []
• # List with repeated elements
repeated_list = [1] * 5 # [1, 1, 1, 1, 1]
• # List of lists (nested lists)
nested_list = [[1, 2], [3, 4]]
1. Creating a List
shopping_list = ['apples', 'oranges', 'bananas',
'cheese']
print(shopping_list)
• This initializes a list called shopping_list with four
string items. Printing shopping_list displays the
entire list.
Accessing Elements
nums = [7, 2, 5, 1, 3]
nums.sort() # Sorts in ascending order
print(nums) # Output: [1, 2, 3, 5, 7]
nums = [7, 2, 5, 1, 3]
sorted_nums = sorted(nums) # Returns a new sorted list
print(sorted_nums) # Output: [1, 2, 3, 5, 7]
print(nums) # Original list remains unchanged: [7, 2, 5,
1, 3]
Sorting student grades
from highest to lowest.
Real-World
Sorting files by date in a
Application file management system.
s
nums = [1, 2, 2, 2, 3, 4, 7]
bisect.insort(nums, 6) # Inserts 6 at the correct
position
print(nums) # Output: [1, 2, 2, 2, 3, 4, 6, 7]
Auto-suggest features:
Searching where a word fits
in a dictionary.
• Slicing is a way to extract a portion of a sequence (list, tuple, string). The basic
syntax is:
sequence[start:stop:step]
• start (optional) → Index to start slicing (default: beginning).
• stop → Index to stop slicing (not included).
• step (optional) → How many elements to skip.
Example 1: Basic slicing
nums = [7, 2, 3, 7, 5, 6, 0, 1]
print(nums[1:5]) # Output: [2, 3, 7, 5]
Real-World
Application Image processing: Cropping
images using slices of pixel
s arrays.
Financial time-series
analysis: Extracting a subset
of historical prices.
A tuple in Python is an
immutable and ordered
collection of elements.
tuple_from_string = tuple('string')
print(tuple_from_string) # Output: ('s',
't', 'r', 'i', 'n', 'g')
Accessing Tuple Elements
tup[1].append(3)
print(tup) # Output: ('foo', [1, 2, 3],
True)
Concatenation and Multiplication
• Since tuples are immutable, they have very few built-in methods.
• Counting occurrences (count)
a = (1, 2, 2, 2, 3, 4, 2)
print(a.count(2)) # Output: 4
When to Use Tuples Instead of Lists?
Feature Tuple List
Mutability ❌ Immutable ✅ Mutable
Performance ✅ Faster ❌ Slower
Memory Usage ✅ Less ❌ More
✅ Hashable (if containing
Hashability ❌ Not Hashable
only immutable items)
print(tup)
print(tup[0:2])
###
Output:
• If the sequences are of different lengths, zip() stops at the shortest one.
Math: 85
Science: 90
History: 78
reversed
nums = [1, 2, 3, 4, 5]
print(list(reversed(nums)))
Output:
[5, 4, 3, 2, 1]
Reversing a String:
• Practical Applications:
text = "hello" • Iterating in reverse without modifying
the original data.
print("".join(reversed(text))) • Implementing undo/rollback
operations in applications.
Output: • Processing logs in reverse order.
"olleh”
Reversing a Tuple:
tuple_data = (10, 20, 30)
print(tuple(reversed(tuple_data)))
(30, 20, 10)
Dictionaries (dict)
A dictionary (dict) is a built-in data structure in Python that stores data in key-
value pairs.
Values: Can be of any data type (e.g., string, list, another dict).
Order: Since Python 3.7, dictionaries maintain the insertion order of keys.
dictionary (or dict
empty_dict = {}
student = {
"name": "Alice",
"age": 20,
"is_passed": True
}
Output:
print(student) {'name': 'Alice', 'age': 20, 'grades': [85, 90, 92], 'is_passed':
True}
Using the dict() Constructor
# Creating a dict from a list of tuples
mapping = dict([('x', 1), ('y', 2)])
print(mapping) # Output: {'x': 1, 'y': 2}
# Using zip to pair two sequences
keys = range(5)
values = reversed(range(5))
mapping = dict(zip(keys, values))
print(mapping) # Output: {0: 4, 1: 3, 2: 2, 3: 1,
4: 0}
Dict Comprehensions
print(d1.get('nonexistent', 'default')) #
Output: 'default'
Inserting and Updating
• The update method lets you merge one dictionary into another:
An unordered collection. When we access all items, they are accessed without
any specific order and we cannot access items using indexes as we do in lists.
Internally use hashing that makes set efficient for search, insert and delete
operations. It gives a major advantage over a list for problems with these
operations.
Mutable, meaning we can add or remove elements after their creation, the
individual elements within the set cannot be changed directly.
Creating a Set
a = {1, 2, 3, 4, 5} b = {3, 4, 5, 6, 7, 8} a | b
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
a.union(b)
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection (& or intersection())
a & b
# Output: {3, 4, 5}
a.intersection(b)
# Output: {3, 4, 5}
In-place Operations (Efficient for Large
Sets)
• |= (Update set with union)
• &= (Update set with intersection)
c = a.copy()
c |= b # c now contains union of a and b
print(c) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
d = a.copy()
d &= b # d now contains intersection of a and b
print(d) # Output: {3, 4, 5}
Set Properties
my_data = [1, 2, 3, 4]
my_set = {tuple(my_data)}
print(my_set) # Output: {(1, 2, 3, 4)}
Subset and Superset Checks
a_set = {1, 2, 3, 4, 5}
print({1, 2, 3}.issubset(a_set)) # Output: True
print(a_set.issuperset({1, 2, 3})) # Output: True
• Set Equality
• Sets are equal if they contain the same elements (order doesn’t matter).