Python Basics
Python Basics
1 Operations on List
[1]: # Slicing
# Define a list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[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]
2
'kiwi', 'elderberry']
3
After extend: ['apple', 'kiwi', 'banana', 'cherry', 'dragonfruit', 'mango',
'nectarine']
4
Before clear: ['apple', 'elderberry']
After clear: []
# 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:")
5
Item at index 3 is cantaloupe
Item at index 4 is kiwi
Item at index 5 is 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
# 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: []
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)
# 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'
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
Joining tuples:
Joined tuple: ('grapes', 'kiwi', 'banana', 'cherry', 'mangoes', 'orange',
'peach')
Tuple methods:
Count of 'kiwi': 1
Index of 'cherry': 3
# 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
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)
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)])
11
Removing items from dictionary:
Updated 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)
12
# Remove set items
print("\nRemoving items from set:")
fruits_set.remove('kiwi')
print("Updated set: ", fruits_set)
# 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)
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'}
Hello, World!
[23]: # Here's a slightly more complex example, where the function takes a parameter:
def greet(name):
print("Hello, " + name + "!")
Hello, Alice!
14
[24]: def add_numbers(num1, num2):
return num1 + num2
15