Intro_to_Python_DataStructures_and_Functions
November 15, 2024
1 Operations on List
[1]: # Slicing
# Define a list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get the first 5 items
print(numbers[:5]) # Output: [0, 1, 2, 3, 4]
# Get the items from index 5 to the end
print(numbers[5:]) # Output: [5, 6, 7, 8, 9]
# Get the last 3 items
print(numbers[-3:]) # Output: [7, 8, 9]
# Get the items from index 2 to index 5 (exclusive)
print(numbers[2:5]) # Output: [2, 3, 4]
# Get every second item in the range from index 1 to index 6
print(numbers[1:6:2]) # Output: [1, 3, 5]
# Reverse the list
print(numbers[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Get every second item in the reversed list
print(numbers[::-2]) # Output: [9, 7, 5, 3, 1]
# Get a sublist in reverse order (e.g., items from index 2 to index 6)
print(numbers[6:1:-1]) # Output: [6, 5, 4, 3, 2]
# Slicing with negative step, starting from end
print(numbers[8:2:-2]) # Output: [8, 6, 4]
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[7, 8, 9]
[2, 3, 4]
1
[1, 3, 5]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 7, 5, 3, 1]
[6, 5, 4, 3, 2]
[8, 6, 4]
[6]: # Example List
fruits = ['apple', 'banana', 'cherry', 'apple', 'elderberry']
# Change an item by index
print("Before changing item by index: ", fruits)
fruits[0] = 'kiwi'
print("After changing item by index: ", fruits) # Output: ['kiwi', 'banana',␣
↪'cherry', 'apple', 'elderberry']
# Change multiple items by slicing
print("\nBefore changing items by slicing: ", fruits)
fruits[1:3] = ['blackcurrant', 'cantaloupe']
print("After changing items by slicing: ", fruits) # Output: ['kiwi',␣
↪'blackcurrant', 'cantaloupe', 'apple', 'elderberry']
# Change items based on condition
print("\nBefore changing items based on condition: ", fruits)
fruits = ['kiwi' if fruit == 'apple' else fruit for fruit in fruits]
print("After changing items based on condition: ", fruits) # Output: ['kiwi',␣
↪'blackcurrant', 'cantaloupe', 'kiwi', 'elderberry']
# Use list method to replace
print("\nBefore using list method to replace: ", fruits)
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'kiwi') # Insert 'kiwi' at index 1
fruits.pop(2) # Remove the item at index 2 ('banana')
print("After using list method to replace: ", fruits) # Output: ['apple',␣
↪'kiwi', 'cherry']
Before changing item by index: ['apple', 'banana', 'cherry', 'apple',
'elderberry']
After changing item by index: ['kiwi', 'banana', 'cherry', 'apple',
'elderberry']
Before changing items by slicing: ['kiwi', 'banana', 'cherry', 'apple',
'elderberry']
After changing items by slicing: ['kiwi', 'blackcurrant', 'cantaloupe',
'apple', 'elderberry']
Before changing items based on condition: ['kiwi', 'blackcurrant',
'cantaloupe', 'apple', 'elderberry']
After changing items based on condition: ['kiwi', 'blackcurrant', 'cantaloupe',
2
'kiwi', 'elderberry']
Before using list method to replace: ['kiwi', 'blackcurrant', 'cantaloupe',
'kiwi', 'elderberry']
After using list method to replace: ['apple', 'kiwi', 'cherry']
[4]: # Example List
fruits = ['apple', 'banana', 'cherry']
# Adding an item to the end of the list using append()
print("Before append: ", fruits)
fruits.append('dragonfruit')
print("After append: ", fruits) # Output: ['apple', 'banana', 'cherry',␣
↪'dragonfruit']
# Adding an item at a specific position using insert()
print("\nBefore insert: ", fruits)
fruits.insert(1, 'kiwi')
print("After insert: ", fruits) # Output: ['apple', 'kiwi', 'banana',␣
↪'cherry', 'dragonfruit']
# Adding multiple items to the end of the list using extend()
print("\nBefore extend: ", fruits)
fruits.extend(['mango', 'nectarine'])
print("After extend: ", fruits) # Output: ['apple', 'kiwi', 'banana',␣
↪'cherry', 'dragonfruit', 'mango', 'nectarine']
# Adding multiple items at a specific position by slicing
print("\nBefore slicing: ", fruits)
fruits[2:2] = ['blackcurrant', 'cantaloupe']
print("After slicing: ", fruits) # Output: ['apple', 'kiwi', 'blackcurrant',␣
↪'cantaloupe', 'banana', 'cherry', 'dragonfruit', 'mango', 'nectarine']
# Adding items from another list using the "+" operator
print("\nBefore adding another list: ", fruits)
other_fruits = ['orange', 'papaya']
fruits = fruits + other_fruits
print("After adding another list: ", fruits) # Output: ['apple', 'kiwi',␣
↪'blackcurrant', 'cantaloupe', 'banana', 'cherry', 'dragonfruit', 'mango',␣
↪'nectarine', 'orange', 'papaya']
Before append: ['apple', 'banana', 'cherry']
After append: ['apple', 'banana', 'cherry', 'dragonfruit']
Before insert: ['apple', 'banana', 'cherry', 'dragonfruit']
After insert: ['apple', 'kiwi', 'banana', 'cherry', 'dragonfruit']
Before extend: ['apple', 'kiwi', 'banana', 'cherry', 'dragonfruit']
3
After extend: ['apple', 'kiwi', 'banana', 'cherry', 'dragonfruit', 'mango',
'nectarine']
Before slicing: ['apple', 'kiwi', 'banana', 'cherry', 'dragonfruit', 'mango',
'nectarine']
After slicing: ['apple', 'kiwi', 'blackcurrant', 'cantaloupe', 'banana',
'cherry', 'dragonfruit', 'mango', 'nectarine']
Before adding another list: ['apple', 'kiwi', 'blackcurrant', 'cantaloupe',
'banana', 'cherry', 'dragonfruit', 'mango', 'nectarine']
After adding another list: ['apple', 'kiwi', 'blackcurrant', 'cantaloupe',
'banana', 'cherry', 'dragonfruit', 'mango', 'nectarine', 'orange', 'papaya']
[7]: # Example List
fruits = ['apple', 'kiwi', 'blackcurrant', 'cantaloupe', 'kiwi', 'elderberry']
# Removing an item by index using pop()
print("Before pop: ", fruits)
removed = fruits.pop(1)
print(f"After pop: {fruits}, removed item: {removed}") # Output: ['apple',␣
↪'blackcurrant', 'cantaloupe', 'kiwi', 'elderberry'], removed item: kiwi
# Removing an item by value using remove()
print("\nBefore remove: ", fruits)
fruits.remove('blackcurrant')
print("After remove: ", fruits) # Output: ['apple', 'cantaloupe', 'kiwi',␣
↪'elderberry']
# Removing multiple items by slicing
print("\nBefore slicing: ", fruits)
del fruits[1:3]
print("After slicing: ", fruits) # Output: ['apple', 'elderberry']
# Removing all items using clear()
print("\nBefore clear: ", fruits)
fruits.clear()
print("After clear: ", fruits) # Output: []
Before pop: ['apple', 'kiwi', 'blackcurrant', 'cantaloupe', 'kiwi',
'elderberry']
After pop: ['apple', 'blackcurrant', 'cantaloupe', 'kiwi', 'elderberry'],
removed item: kiwi
Before remove: ['apple', 'blackcurrant', 'cantaloupe', 'kiwi', 'elderberry']
After remove: ['apple', 'cantaloupe', 'kiwi', 'elderberry']
Before slicing: ['apple', 'cantaloupe', 'kiwi', 'elderberry']
After slicing: ['apple', 'elderberry']
4
Before clear: ['apple', 'elderberry']
After clear: []
[8]: # Example List
fruits = ['apple', 'kiwi', 'blackcurrant', 'cantaloupe', 'kiwi', 'elderberry']
# Looping through a list using a for loop
print("Looping through list using a for loop:")
for fruit in fruits:
print(fruit)
# Looping through a list by index using a for loop and range()
print("\nLooping through list by index using a for loop and range():")
for i in range(len(fruits)):
print(f"Item at index {i} is {fruits[i]}")
# Looping through a list and creating a new list (list comprehension)
print("\nLooping through a list and creating a new list (list comprehension):")
capitalized_fruits = [fruit.upper() for fruit in fruits]
print(capitalized_fruits) # Output: ['APPLE', 'KIWI', 'BLACKCURRANT',␣
↪'CANTALOUPE', 'KIWI', 'ELDERBERRY']
# Looping through a list using enumerate() to get both the index and the value
print("\nLooping through a list using enumerate() to get both the index and the␣
↪value:")
for i, fruit in enumerate(fruits):
print(f"Item at index {i} is {fruit}")
# Looping through a list using a while loop
print("\nLooping through a list using a while loop:")
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
Looping through list using a for loop:
apple
kiwi
blackcurrant
cantaloupe
kiwi
elderberry
Looping through list by index using a for loop and range():
Item at index 0 is apple
Item at index 1 is kiwi
Item at index 2 is blackcurrant
5
Item at index 3 is cantaloupe
Item at index 4 is kiwi
Item at index 5 is elderberry
Looping through a list and creating a new list (list comprehension):
['APPLE', 'KIWI', 'BLACKCURRANT', 'CANTALOUPE', 'KIWI', 'ELDERBERRY']
Looping through a list using enumerate() to get both the index and the value:
Item at index 0 is apple
Item at index 1 is kiwi
Item at index 2 is blackcurrant
Item at index 3 is cantaloupe
Item at index 4 is kiwi
Item at index 5 is elderberry
Looping through a list using a while loop:
apple
kiwi
blackcurrant
cantaloupe
kiwi
elderberry
[12]: # Original list
fruits = ['grapes', 'apple', 'banana', 'cherry', 'mangoes']
print("Original list: ", fruits)
# List Comprehension
lengths = [len(fruit) for fruit in fruits]
print("\nList comprehension (lengths): ", lengths) # Output: [6, 5, 6, 6, 7]
# Sort Lists
fruits.sort()
print("\nSorted list (ascending): ", fruits) # Output: ['apple', 'banana',␣
↪'cherry', 'grapes', 'mangoes']
fruits.sort(reverse=True)
print("Sorted list (descending): ", fruits) # Output: ['mangoes', 'grapes',␣
↪'cherry', 'banana', 'apple']
# Copy Lists
fruits_copy = fruits.copy()
print("\nCopied list: ", fruits_copy) # Output: ['mangoes', 'grapes',␣
↪'cherry', 'banana', 'apple']
# Join Lists
fruits_extra = ['elderberry', 'fig', 'grapefruit']
6
joined_list = fruits + fruits_extra
print("\nJoined list: ", joined_list) # Output: ['mangoes', 'grapes',␣
↪'cherry', 'banana', 'apple', 'elderberry', 'fig', 'grapefruit']
# List Methods
print("\nList methods:")
fruits.append('honeydew')
print("After append: ", fruits) # Output: ['mangoes', 'grapes', 'cherry',␣
↪'banana', 'apple', 'honeydew']
fruits.remove('banana')
print("After remove: ", fruits) # Output: ['mangoes', 'grapes', 'cherry',␣
↪'apple', 'honeydew']
index = fruits.index('cherry')
print("Index of 'cherry': ", index) # Output: 2
count = fruits.count('apple')
print("Count of 'apple': ", count) # Output: 1
fruits.pop(2)
print("After pop at index 2: ", fruits) # Output: ['mangoes', 'grapes',␣
↪'apple', 'honeydew']
fruits.clear()
print("After clear: ", fruits) # Output: []
Original list: ['grapes', 'apple', 'banana', 'cherry', 'mangoes']
List comprehension (lengths): [6, 5, 6, 6, 7]
Sorted list (ascending): ['apple', 'banana', 'cherry', 'grapes', 'mangoes']
Sorted list (descending): ['mangoes', 'grapes', 'cherry', 'banana', 'apple']
Copied list: ['mangoes', 'grapes', 'cherry', 'banana', 'apple']
Joined list: ['mangoes', 'grapes', 'cherry', 'banana', 'apple', 'elderberry',
'fig', 'grapefruit']
List methods:
After append: ['mangoes', 'grapes', 'cherry', 'banana', 'apple', 'honeydew']
After remove: ['mangoes', 'grapes', 'cherry', 'apple', 'honeydew']
Index of 'cherry': 2
Count of 'apple': 1
After pop at index 2: ['mangoes', 'grapes', 'apple', 'honeydew']
After clear: []
7
2 Tuples
[13]: # Access Tuples
fruits_tuple = ('grapes', 'apple', 'banana', 'cherry', 'mangoes')
print("Original tuple: ", fruits_tuple)
print("\nAccessing elements in tuple:")
print("First fruit: ", fruits_tuple[0]) # Output: 'grapes'
print("Last fruit: ", fruits_tuple[-1]) # Output: 'mangoes'
# Update Tuples
# Tuples are immutable, so we can't directly change an element of a tuple.
# But we can concatenate tuples or convert them to lists, modify them, and then␣
↪convert back to tuples.
print("\nUpdating tuples:")
list_fruits = list(fruits_tuple)
list_fruits[1] = 'kiwi' # Changing 'apple' to 'kiwi'
fruits_tuple = tuple(list_fruits)
print("After updating tuple: ", fruits_tuple) # Output: ('grapes', 'kiwi',␣
↪'banana', 'cherry', 'mangoes')
# Unpack Tuples
print("\nUnpacking tuples:")
fruit1, fruit2, fruit3, fruit4, fruit5 = fruits_tuple
print("Fruit1: ", fruit1) # Output: 'grapes'
print("Fruit2: ", fruit2) # Output: 'kiwi'
print("Fruit3: ", fruit3) # Output: 'banana'
print("Fruit4: ", fruit4) # Output: 'cherry'
print("Fruit5: ", fruit5) # Output: 'mangoes'
Original tuple: ('grapes', 'apple', 'banana', 'cherry', 'mangoes')
Accessing elements in tuple:
First fruit: grapes
Last fruit: mangoes
Updating tuples:
After updating tuple: ('grapes', 'kiwi', 'banana', 'cherry', 'mangoes')
Unpacking tuples:
Fruit1: grapes
Fruit2: kiwi
Fruit3: banana
Fruit4: cherry
Fruit5: mangoes
8
[14]: # Original Tuple
fruits_tuple = ('grapes', 'kiwi', 'banana', 'cherry', 'mangoes')
print("Original tuple: ", fruits_tuple)
# Loop Tuples
print("\nLooping through tuple:")
for fruit in fruits_tuple:
print(fruit)
# Join Tuples
print("\nJoining tuples:")
more_fruits = ('orange', 'peach')
joined_tuple = fruits_tuple + more_fruits
print("Joined tuple: ", joined_tuple) # Output: ('grapes', 'kiwi', 'banana',␣
↪'cherry', 'mangoes', 'orange', 'peach')
# Tuple Methods
print("\nTuple methods:")
count = fruits_tuple.count('kiwi')
print("Count of 'kiwi': ", count) # Output: 1
index = fruits_tuple.index('cherry')
print("Index of 'cherry': ", index) # Output: 3
Original tuple: ('grapes', 'kiwi', 'banana', 'cherry', 'mangoes')
Looping through tuple:
grapes
kiwi
banana
cherry
mangoes
Joining tuples:
Joined tuple: ('grapes', 'kiwi', 'banana', 'cherry', 'mangoes', 'orange',
'peach')
Tuple methods:
Count of 'kiwi': 1
Index of 'cherry': 3
[15]: # Original Tuple
fruits_tuple = ('grapes', 'kiwi', 'banana', 'cherry', 'mangoes', 'kiwi')
print("Original tuple: ", fruits_tuple)
# Tuple Methods
print("\nTuple methods:")
9
# count()
count_kiwi = fruits_tuple.count('kiwi')
print("Count of 'kiwi': ", count_kiwi) # Output: 2
# index()
index_cherry = fruits_tuple.index('cherry')
print("Index of 'cherry': ", index_cherry) # Output: 3
Original tuple: ('grapes', 'kiwi', 'banana', 'cherry', 'mangoes', 'kiwi')
Tuple methods:
Count of 'kiwi': 2
Index of 'cherry': 3
3 Dictionaries
[17]: # Original dictionary
fruits_dict = {'grapes': 5, 'kiwi': 2, 'banana': 6, 'cherry': 8, 'mangoes': 7}
print("Original dictionary: ", fruits_dict)
# Accessing dictionary items
print("\nAccessing dictionary items:")
print("Value of 'banana': ", fruits_dict['banana']) # Output: 6
# Change dictionary items
print("\nChanging dictionary items:")
fruits_dict['banana'] = 10
print("Updated dictionary: ", fruits_dict) # Output: {'grapes': 5, 'kiwi': 2,␣
↪'banana': 10, 'cherry': 8, 'mangoes': 7}
# Adding items to dictionary
print("\nAdding items to dictionary:")
fruits_dict['apple'] = 4
print("Updated dictionary: ", fruits_dict) # Output: {'grapes': 5, 'kiwi': 2,␣
↪'banana': 10, 'cherry': 8, 'mangoes': 7, 'apple': 4}
# Removing items from dictionary
print("\nRemoving items from dictionary:")
fruits_dict.pop('kiwi')
print("Updated dictionary: ", fruits_dict) # Output: {'grapes': 5, 'banana':␣
↪10, 'cherry': 8, 'mangoes': 7, 'apple': 4}
# Looping through a dictionary
print("\nLooping through a dictionary:")
for key, value in fruits_dict.items():
print(key, value)
10
# Dictionary comprehension
print("\nDictionary comprehension:")
prices = {key: value * 2 for key, value in fruits_dict.items()}
print("New dictionary (prices): ", prices) # Output: {'grapes': 10, 'banana':␣
↪20, 'cherry': 16, 'mangoes': 14, 'apple': 8}
# Copying a dictionary
print("\nCopying a dictionary:")
fruits_copy = fruits_dict.copy()
print("Copied dictionary: ", fruits_copy) # Output: {'grapes': 5, 'banana':␣
↪10, 'cherry': 8, 'mangoes': 7, 'apple': 4}
# Merging dictionaries
print("\nMerging dictionaries:")
extra_fruits = {'peach': 3, 'orange': 4}
fruits_dict.update(extra_fruits)
print("Updated dictionary: ", fruits_dict) # Output: {'grapes': 5, 'banana':␣
↪10, 'cherry': 8, 'mangoes': 7, 'apple': 4, 'peach': 3, 'orange': 4}
# Dictionary methods
print("\nDictionary methods:")
keys = fruits_dict.keys()
print("Keys: ", keys) # Output: dict_keys(['grapes', 'banana', 'cherry',␣
↪'mangoes', 'apple', 'peach', 'orange'])
values = fruits_dict.values()
print("Values: ", values) # Output: dict_values([5, 10, 8, 7, 4, 3, 4])
items = fruits_dict.items()
print("Items: ", items) # Output: dict_items([('grapes', 5), ('banana', 10),␣
↪('cherry', 8), ('mangoes', 7), ('apple', 4), ('peach', 3), ('orange', 4)])
Original dictionary: {'grapes': 5, 'kiwi': 2, 'banana': 6, 'cherry': 8,
'mangoes': 7}
Accessing dictionary items:
Value of 'banana': 6
Changing dictionary items:
Updated dictionary: {'grapes': 5, 'kiwi': 2, 'banana': 10, 'cherry': 8,
'mangoes': 7}
Adding items to dictionary:
Updated dictionary: {'grapes': 5, 'kiwi': 2, 'banana': 10, 'cherry': 8,
'mangoes': 7, 'apple': 4}
11
Removing items from dictionary:
Updated dictionary: {'grapes': 5, 'banana': 10, 'cherry': 8, 'mangoes': 7,
'apple': 4}
Looping through a dictionary:
grapes 5
banana 10
cherry 8
mangoes 7
apple 4
Dictionary comprehension:
New dictionary (prices): {'grapes': 10, 'banana': 20, 'cherry': 16, 'mangoes':
14, 'apple': 8}
Copying a dictionary:
Copied dictionary: {'grapes': 5, 'banana': 10, 'cherry': 8, 'mangoes': 7,
'apple': 4}
Merging dictionaries:
Updated dictionary: {'grapes': 5, 'banana': 10, 'cherry': 8, 'mangoes': 7,
'apple': 4, 'peach': 3, 'orange': 4}
Dictionary methods:
Keys: dict_keys(['grapes', 'banana', 'cherry', 'mangoes', 'apple', 'peach',
'orange'])
Values: dict_values([5, 10, 8, 7, 4, 3, 4])
Items: dict_items([('grapes', 5), ('banana', 10), ('cherry', 8), ('mangoes',
7), ('apple', 4), ('peach', 3), ('orange', 4)])
4 Sets
[18]: # Original set
fruits_set = {'grapes', 'kiwi', 'banana', 'cherry', 'mangoes'}
print("Original set: ", fruits_set)
# Access set items
# We cannot access individual items in a set directly as sets are unordered,
# but we can loop through the set or convert it to a list/tuple and access them.
print("\nAccessing set items (as a list):")
fruits_list = list(fruits_set)
print("First item: ", fruits_list[0])
# Add set items
print("\nAdding items to set:")
fruits_set.add('apple')
print("Updated set: ", fruits_set)
12
# Remove set items
print("\nRemoving items from set:")
fruits_set.remove('kiwi')
print("Updated set: ", fruits_set)
# Looping through a set
print("\nLooping through a set:")
for fruit in fruits_set:
print(fruit)
# Set comprehension
print("\nSet comprehension:")
lengths = {len(fruit) for fruit in fruits_set}
print("New set (lengths): ", lengths)
# Copying a set
print("\nCopying a set:")
fruits_copy = fruits_set.copy()
print("Copied set: ", fruits_copy)
# Join sets
print("\nJoining sets:")
more_fruits = {'orange', 'peach'}
all_fruits = fruits_set.union(more_fruits)
print("Joined set: ", all_fruits)
# Set methods
print("\nSet methods:")
fruits_set.add('pear')
print("After add: ", fruits_set)
fruits_set.remove('apple')
print("After remove: ", fruits_set)
Original set: {'grapes', 'kiwi', 'mangoes', 'cherry', 'banana'}
Accessing set items (as a list):
First item: grapes
Adding items to set:
Updated set: {'grapes', 'apple', 'kiwi', 'mangoes', 'cherry', 'banana'}
Removing items from set:
Updated set: {'grapes', 'apple', 'mangoes', 'cherry', 'banana'}
Looping through a set:
grapes
apple
13
mangoes
cherry
banana
Set comprehension:
New set (lengths): {5, 6, 7}
Copying a set:
Copied set: {'grapes', 'apple', 'cherry', 'banana', 'mangoes'}
Joining sets:
Joined set: {'grapes', 'apple', 'cherry', 'orange', 'peach', 'banana',
'mangoes'}
Set methods:
After add: {'grapes', 'apple', 'pear', 'mangoes', 'cherry', 'banana'}
After remove: {'grapes', 'pear', 'mangoes', 'cherry', 'banana'}
5 User Defined Functions in Python
Functions
Built-in Functions
User Defined Functions
User Defined Functions is a block of reusable code that performs a specific task. You define a
function using the def keyword, followed by the function name, parentheses (), and a colon :. Inside
the parentheses, you can specify any parameters your function will take. The function's code block
is indented under the function definition.
[22]: def greet():
print("Hello, World!")
# Calling the function
greet() # Output: Hello, World!
Hello, World!
[23]: # Here's a slightly more complex example, where the function takes a parameter:
def greet(name):
print("Hello, " + name + "!")
# Calling the function
greet("Alice") # Output: Hello, Alice!
Hello, Alice!
14
[24]: def add_numbers(num1, num2):
return num1 + num2
# Calling the function
result = add_numbers(3, 5)
print(result) # Output: 8
15