Lecture Python5
Lecture Python5
index() method is used for finding the index position of an element within a list
my_list = ["apple", "banana", "cherry", "banana", "mango"]
index_of_banana = my_list.index("banana")
print(index_of_banana) # output : 1
Modifying Lists:
#Lists are mutable, meaning you can change their content after creation.
Assigning to an index:
fruits[1] = "mango" # Replace "banana" with "mango" at index 1
Appending elements:
#append(element) adds an element to the end of the list.
#extend(iterable) extends the list by adding all elements from another iterable
(like another list or a string).
fruits.append("kiwi")
numbers.extend([6, 7, 8])
print(fruits);print(numbers)
# Output:
['apple', 'banana', 'cherry', 'kiwi']
[1, 2, 3, 4, 5, 6, 7, 8]
Inserting elements:
#insert(index, element) inserts an element at a specific index, shifting existing
elements to the right.
fruits.insert(2, "orange") # Insert "orange" at index 2
Removing elements: (canceled slide)
#remove(element) removes the first occurrence of the specified element.
pop(index) removes the element at the given index (defaults to the last element if no
index is provided).
numbers.remove(4) # Remove the first occurrence of 4
removed_fruit = fruits.pop(1) # Remove and store the element at index 1
Sorts by default in ascending order.
The .sort() method is a built-in function in Python used to sort elements of a list.
numbers = [3, 1, 4, 5, 2]
numbers.sort() # Sorts in ascending order (default)
print(numbers) # Output: [1, 2, 3, 4, 5]
numbers.sort(reverse=True) # Sorts in descending order
print(numbers) # Output: [5, 4, 3, 2, 1]
Reverse the order of elements
y= ["hello", 10.5, True]
y.reverse()
print(y) #output [True,10.5,"hello"]
The .clear() method in Python is used to remove all elements from a list. It effectively
empties the list.
numbers = [1, 2, 3, 4, 5]
numbers.clear()
print(numbers) # Output: [] (empty list)
(canceled slide)
The .copy() method in Python is used to create a shallow copy of a list. This means it creates a
new list with the same elements as the original list, but the elements themselves are still
references to the original objects.
original_list = [1, 2, [3, 4]] # List containing a nested list
new_list = original_list.copy()
print(original_list) # Output: [1, 2, [3, 4]]
print(new_list) # Output: [1, 2, [3, 4]] (shallow copy)
new_list[2].append(5) # Modify nested list in the new list
print(original_list) # Output: [1, 2, [3, 4, 5]] (original list also modified)
print(new_list) # Output: [1, 2, [3, 4, 5]]
For creating a deep copy where nested objects are also copied independently, you'll need to use
the copy.deepcopy function from the copy module.
import copy
original_list = [1, 2, [3, 4]]
copied_list = copy.deepcopy(original_list)
original_list[2][0] = 99 # Modify nested element in original_list
print(original_list) # Output: [1, 2, [99, 4]]
print(copied_list) # Output: [1, 2, [3, 4]] # Remains unchanged
The .count() method in Python is a built-in method that counts the number of times a specified element
appears in a list or string. It's a handy way to check the frequency of elements within your data.
numbers = [1, 2, 2, 3, 4, 2, 1, 4, 5]
# Count the number of occurrences of 2 in the list
number_count=numbers.count(2)
# Print the number of occurrences
print(number_count)
List Operations:
Concatenation: The + operator combines two lists into a new list.
all_fruits = fruits + numbers # output ['apple', "banana", 'cherry', 1, 2, 3, 4, 5]
Repetition
# * operator: Create a new list with elements repeated a specific number of times.
numbers = [1, 2, 3]
repeated = numbers * 3
print(repeated) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Length:
#len() function: Determine the number of elements in the list.
print(len(fruits)) # Output: 3
Minimum and Maximum:
#min() and max() functions: Find the smallest and largest element, respectively (works for comparable elements).
print(min(numbers)) # Output: 3.14 (assuming numerical comparison)
Membership Testing:
#in and not in operator: Check if an element exists in the tuple.
print("apple" in fruits) # Output: True
Tuple is an ordered, immutable collection of items. It's similar to a list in terms of storing multiple
items in a single variable, but with a key difference: tuples cannot be changed after creation:
#Tuple are created by enclosing a comma-separated sequence of items within
parentheses ():
my_tuple = (1, "apple", 3.14) # parentheses not necessary
Empty_tuple = ()
Common Use Cases
person = ("Alice", 30, "Seattle") #Storing related data together: Name, age, city
weekdays = ("Monday", "Tuesday", "Wednesday") #Representing fixed sets of values
Modifying tuple:
#Tuples are immutable, meaning their contents cannot be modified after creation. This makes
them useful for representing fixed data sets that shouldn't be altered.
my_tuple[0] = 2 # TypeError: 'tuple' object does not support item assignment
Accessing Elements: (same as the list)
#Elements in a tuple are accessed using zero-based indexing, just like lists. The first
element has an index of 0, the second has an index of 1, and so on:
print(my_tuple[0]) # Output: 1
print(my_tuple[1]) # Output: apple
print(my_tuple[3]) # IndexError: tuple index out of range
#Slicing: Extract a sub-sequence using colon : syntax. Similar to lists.
print(my_tuple[1:3]) # Output: ("apple", 3.14)
(same as the list)
Membership Testing:
#in and not in operator: Check if an element exists in the tuple.
print("apple" in my_tuple) # Output: True
Concatenation:
# + operator: Combine two tuples into a new one.
fruits = ("apple", "banana")
colors = ("red", "yellow")
combo = fruits + colors
print(combo) # Output: ("apple", "banana", "red", "yellow")
Repetition
# * operator: Create a new tuple with elements repeated a specific number of times.
numbers = (1, 2, 3)
repeated = numbers * 3
print(repeated) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Length:
#len() function: Determine the number of elements in the tuple.
print(len(my_tuple)) # Output: 3
Minimum and Maximum:
#min() and max() functions: Find the smallest and largest element, respectively (works for comparable elements).
print(min(my_tuple)) # Output: 3.14 (assuming numerical comparison)
Converting Lists to Tuples
#The tuple() function is the most straightforward way to create a tuple from an existing
list. It accepts an iterable (like a list) as an argument and returns a new tuple containing
the same elements.
my_list = [1, "apple", 3.14]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, "apple", 3.14)
Converting Tuples to Lists
my_tuple = (10, "hello", 3.14)
my_list = list(my_tuple)
print(my_list) # Output: [10, "hello", 3.14]
Dictionaries are powerful data structures used to store collections of items in a
key-value format. Unlike lists and tuples that use indexes for accessing elements,
dictionaries associate data with unique keys, providing a more flexible and
efficient way to organize information.
#You can create dictionaries using curly braces {} and separating key-value
pairs with colons :
fruits = {"apple": "red", "banana": "yellow", "orange": "citrus"}
Empty_dict = {}
#Keys: Keys act as unique identifiers for each value. They must be immutable
data types like strings, numbers, or tuples
#Values: Values can be any data type, including strings, numbers, lists,
dictionaries, or custom objects.
Accessing Elements:
#To access a value, use the corresponding key within square brackets []:
print(fruits["apple"]) # Output: red
Adding or Updating Elements:
#You can add new key-value pairs or modify existing ones directly:
fruits["grape"] = "purple" # Add a new key-value pair
fruits["banana"] = "yellow and creamy" # Update an existing value
Removing Elements:(canceled item)
del fruits["orange"] #This permanently deletes the key-value pair.
removed_value = fruits.pop("grape") #pop() method: This removes and returns the
value associated with the specified key.
print(removed_value) # Output: purple
Common Operations on Dictionaries:
#len(my_dict): Get the number of key-value pairs in the dictionary.
#key in my_dict: Check if a specific key exists in the dictionary.
#my_dict.get(key, default_value): Retrieve a value by key, providing a default value if
the key is not found.
#my_dict.keys(), my_dict.values(), my_dict.items(): Get sets of keys, values, and key-
value pairs (tuples) as separate iterables, respectively.
#for key, value in my_dict.items():: Loop through key-value pairs using a for loop.
print(fruits.items()) #output dict_items([('apple', 'red'), ('banana', 'yellow'), ('orange',
'citrus')])
for name, des in fruits.items():
print(f"{name}: {des}")
#output
apple: red
banana: yellow
orange: citrus
For Loop
Use case: Iterate over a sequence of items like lists, tuples, or strings.
Syntax:
for item in sequence:
# code to be executed for each item
#Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: #(use any name or symbol for example fruit)
print(fruit)
# This code will print each fruit on a new line:
# apple
# banana
# Cherry
#Examples:
Use for loops when you know the exact number of iterations beforehand (iterating
through a sequence).
Use while loops when the number of iterations is unknown, or the loop needs to
continue until a specific condition is met.
Both loops can utilize break to exit the loop prematurely and continue to skip the
current iteration and move to the next.
While loops can optionally include an else clause that executes only when the loop
terminates normally (not due to break).
Example
fruits = ["apple", "banana", "cherry", "orange", "mango"]
# Break example: Exit after finding a specific fruit
for fruit in fruits:
if fruit == "cherry":
print(f"Found {fruit}, exiting loop!")
break # Exit the loop after finding cherry
else:
print(f"Checking fruit: {fruit}")
# Continue example: Skip even-numbered fruits
for i, fruit in enumerate(fruits): # Use enumerate for index and item
if i % 2 == 0: # Check if index is even
continue # Skip to the next iteration for even indexes
print(f"Processing fruit: {fruit} (index: {i})")
# Else example (won't execute here due to break in first loop)
else:
print("Finished iterating through all fruits!")
Example
user_input = ""
while user_input.lower() != "quit": # Loop until user enters "quit"
user_input = input("Enter a message (type 'quit' to exit): ")
if user_input.lower() == "quit":
print("Exiting loop...")
break # Exit the loop when user enters "quit"
else:
print(f"You entered: {user_input}")
# Else example: Executes after successful loop termination (not due to break)
else:
print("Thanks for using the program!")
Def function
The def keyword in Python is used to define functions. A function is a named block of
code that performs a specific task.
Syntax:
def function_name(parameters): #function_name: This is the name you give to your function.
#parameters: These are optional arguments that you can pass to the function
# Function body ( indented code block ) # This is the indented block of code that contains the statements
# Optionally, a return statement #A function can optionally use a return statement to send a value back to the
caller when the function execution finishes.
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!