# Example of a simple list
my_list = [2, 2, 1, 3, 6, 8, 7, 12]
print(my_list)
# List with mixed data types
mixed_list = [1, "Hello", 3.14, True]
print(mixed_list)[2, 2, 1, 3, 6, 8, 7, 12]
[1, 'Hello', 3.14, True]
In Python, a list is a versatile and widely used data structure that allows you to store an ordered collection of items. These items can be of any data type, including integers, floats, strings, or even other lists. Lists are mutable, meaning that their content can be changed after they are created, which makes them a powerful tool for handling dynamic data.
You can create a list by placing the elements inside square brackets [], separated by commas.
# Example of a simple list
my_list = [2, 2, 1, 3, 6, 8, 7, 12]
print(my_list)
# List with mixed data types
mixed_list = [1, "Hello", 3.14, True]
print(mixed_list)[2, 2, 1, 3, 6, 8, 7, 12]
[1, 'Hello', 3.14, True]
You can find the length of a list. This is super important!
print(len(my_list))8
You can access elements in a list using indexing, where the first element has an index of 0.
Before running the following code, what do you think will be the output?
# Accessing elements
print(my_list[0])
print(mixed_list[1]) Since lists are mutable, you can modify their elements.
# Changing an element
my_list[2] = 10
print(my_list) [2, 2, 10, 3, 6, 8, 7, 12]
Adding and removing elements:
# Adding an element
my_list.append(6)
print(my_list)
# Removing an element
my_list.remove(10)
print(my_list)
# Removing an element by index
my_list.pop(2)
print(my_list) [2, 2, 10, 3, 6, 8, 7, 12, 6]
[2, 2, 3, 6, 8, 7, 12, 6]
[2, 2, 6, 8, 7, 12, 6]
Slicing:
# Slicing the list
sub_list = my_list[1:3]
print(sub_list) [2, 6]
More examples:
# Creating a list of fruits
fruits = ["apple", "banana", "cherry"]
# Adding a fruit to the list
fruits.append("date")
# Changing an element in the list
fruits[1] = "blueberry"
# Removing an element
fruits.remove("cherry")
# Slicing the list
some_fruits = fruits[1:3]
# Output the final lists
print(fruits) # Output: ['apple', 'blueberry', 'date']
print(some_fruits) # Output: ['blueberry', 'date']['apple', 'blueberry', 'date']
['blueberry', 'date']
In Python, if statements are used for conditional execution of code blocks. An if statement evaluates a condition (an expression that returns True or False), and if the condition is True, the block of code associated with the if statement is executed. If the condition is False, the code block is skipped.
Example:
x = 10
if x > 5:
print("x is greater than 5")x is greater than 5
You can also provide an alternative block of code to execute if the condition is False using an else statement.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")x is not greater than 5
You can also use logical operators:
x = 8
y = 12
if x > 5 and y > 10:
print("Both conditions are True")
if x > 10 or y > 10:
print("At least one condition is True")
if not x > 10:
print("x is not greater than 10")Both conditions are True
At least one condition is True
x is not greater than 10
In this example, the condition ‘age >= 18’ is checked:
What do you think will be the output?
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status) What do you think will be the output?
a = 10
b = 20
max_value = a if a > b else b
print(max_value)20
A for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in the sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)apple
banana
cherry
for Loops using numbers:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)1
2
3
4
5
Try this! Reverse the list ‘numbers’ and re-run the loop.
The range() function is commonly used with for loops to generate a sequence of numbers.
for i in range(5):
print(i)0
1
2
3
4
In Python there are built-in function like the one we just saw (range()) and they can also be written.
Here are some examples:
def square(x):
return x * x
print(square(5))25
def multiply(x, y):
"""This function multiplies two numbers."""
return x * y
print(multiply(3, 4))12
Example of a Complete Function
def calculate_area(radius):
"""This function calculates the area of a circle given its radius."""
pi = 3.14159
return pi * (radius ** 2)
# Calling the function
area = calculate_area(5)
print(f"The area of the circle is: {area}")The area of the circle is: 78.53975
Given a list consisting of the elements 10, 20, 33, 46, and 55, write a Python code to display the numbers that are divisible by 5.
Given the following list of fruits, add “tomato” to the end of the list. Then add “apple” to the third position.
Ben starts with a list of numbers: [4, 8, 12, 16]. He reassigns the first three elements using slicing and writes:
aList = [4, 8, 12, 16]
aList[1:4] = [20, 24, 28]
print(aList)What will the final list look like?
Isabella wants to add [4, 5] to her list x = [1, 2, 3], so she uses x.append([4, 5]). What will the list look like after, and how does append() behave when adding another list?
How do you get the last item in a list using indexing? Demonstrate by writing a code that will reverse your solution to question 4.
What is the difference between .append() and + when adding to a list?
What does it mean that lists are mutable in Python?
What are square brackets used for in Python? Give two examples.
Write a line of code that prints the number of items in this list: nums = [4, 8, 15, 16]
You have the string “anaconda” called str, and you slice it using str[1:3]. What will this return, and how does slicing work with start and end indices in Python?
As a second part to the previous question - what code would you use to access the “c”, “o”, and “d” elements?
Sam wants to get the last two numbers from a list [5, 10, 15, 25]. He uses negative slicing: alist[-2:]. What does this return, and how does negative indexing work in Python?
Explain the difference between .append() and .insert() for lists.
In your own words, explain the difference between .pop() and .remove() when working with lists.
Write a Python code to remove characters from a string (called word) from 0 to n characters and return a new string.
Write a Python program to calculate the difference between a given number and 17. If the number is greater than 17, return twice the difference.
Write a Python loop that builds a list of squares for numbers 1 through 5. Then explain what the final list will look like.
What does x += 1 do in a loop?
Select which is true for a for loop.
Can you use an else block with a for loop in Python? Try writing a short loop that prints numbers from 1 to 4 and also prints “Loop done!” at the end using else. Explain when the else block runs.
What does range(1, 10, 2) return?
The code is supposed to print numbers from 5 to 1. Fix the error.
for i in range(5, 1):
print(i)total = 0
for i in range(1, 5):
total += i
print(total)Write a Python program that calculates the area of a circle based on the radius entered by the user.
Given the following code with a global variable and a function, explain why the output is different inside and outside the function.
salary = 8000
def printSalary():
salary = 12000
print("Salary:", salary)
printSalary()
print("Salary:", salary)Sophie defines a function to calculate a result, but when she calls it, nothing shows up in the console. What are two possible reasons this might happen in Python?
The function is meant to return the square of a number. Why does it return “None” and how would you fix it?
def square(x):
x * x
print(square(4))x = 100
def show():
x = 50
print("Inside:", x)
show()
print("Outside:", x)def multiply(a, b=2):
return a * b
result = multiply(4)
print(result)If he runs multiply(4), what will the function return and why?
def calculate(num1, num2=4):
res = num1 * num2
print(res)
calculate(5, 6)What will be printed, and how does Python handle default values in this case?