Friday, May 15, 2026

What is a List in Python?

What is a List in Python?

A list is a container that holds multiple items in a single variable, in a specific order.

How to Create a Lists:

# Empty list
my_list = []

# List of numbers
numbers = [1, 2, 3, 4, 5]

# List of strings
names = ["Alice", "Bob", "Charlie"]

# Mixed list (different data types)
mixed = [1, "hello", 3.14, True]

# List inside a list (nested)
nested = [[1, 2], [3, 4], [5, 6]]

Accessing Items — Indexing

fruits = ["apple", "banana", "mango", "orange"]

#index 0 1 2 3

print(fruits[0]) # apple ← first item
print(fruits[2]) # mango ← third item
print(fruits[-1]) # orange ← last item (negative index)
print(fruits[-2]) # mango ← second from last

Slicing a List

fruits = ["apple", "banana", "mango", "orange", "grape"]

print(fruits[1:3]) # ["banana", "mango"] ← index 1 to 2
print(fruits[:3]) # ["apple","banana","mango"] ← start to index 2
print(fruits[2:]) # ["mango","orange","grape"] ← index 2 to end
print(fruits[::2]) # ["apple","mango","grape"] ← every 2nd item

Most Used List Methods

fruits = ["apple", "banana", "mango"]

# ADD items

fruits.append("orange") # adds to END → ["apple","banana","mango","orange"]
fruits.insert(1, "grape") # adds at index 1 → ["apple","grape","banana"...]

# REMOVE items

fruits.remove("banana") # removes by VALUE
fruits.pop() # removes LAST item
fruits.pop(0) # removes item at index 0

# FIND items

print(len(fruits)) # total count of items
print(fruits.index("mango")) # finds index of "mango"
print("apple" in fruits) # True/False — does it exist?

# SORT items

fruits.sort() # sorts A→Z or small→big
fruits.sort(reverse=True) # sorts Z→A or big→small
fruits.reverse() # reverses the order

# COPY & CLEAR

copy = fruits.copy() # makes a copy of the list
fruits.clear() # empties the entire list

Looping Through a List

fruits = ["apple", "banana", "mango"]

# Basic loop
for fruit in fruits:
print(fruit)

# apple
# banana
# mango

# Loop with index

for i, fruit in enumerate(fruits):
print(i, fruit)

# 0 apple
# 1 banana
# 2 mango

# creating a simple list in python

groceries = ["Apple", "Banana", "Pineapple", "Cherry"]
print(groceries)

# Accessing elements

groceries = ["milk", "noodles", "bread"]
print(groceries[2])
print(groceries[-1])

# Modifying a list:

my_list = ["apple", "banana", "cherry", "pineapple"]
print(my_list)

my_list[0] = "strawberry"
print(my_list)

# Adding elements:

my_list = ["apple", "banana", "cherry"]
my_list.append("grapes") # add grapes
print(my_list)

# Insert elements:

my_list = ["apple", "banana", "cherry", "kiwi"]
print(my_list)
my_list.insert(1, "raspberry") # insert raspberry
print(my_list)

# Removing elements (using 3 methods)

1)

my_list = ["apple", "banana", "berry", "cherry"]
print(my_list)
my_list.remove ("apple") # remove apple
print(my_list)

2)

my_list = ["apple", "banana", "berry", "cherry"]
print(my_list)
my_list.pop() # it will remove the last value "cherry"
print(my_list)

3)

my_list = ["apple", "banana", "berry", "cherry"]
print(my_list)
del my_list[1]
print(my_list)

# Length and looping:

my_list = ["apple", "banana", "berry", "cherry"]
print(my_list)
print(len(my_list)
for item in my_list
print(item)

# List slicing:

my_list = ["apple", "banana", "berry", "cherry"]
print(my_list)
print(my_list[1:3])

# Sorting and Reversing:

num = [2,4,6,3,0,11,19,22,35]
num.sort()
print(num)
rum.reverse()
print(num)

What is a Function in Python?

What is a Function in Python?

A function is a reusable block of code that runs only when you call it.

Basic Syntax

# DEFINING a function
def function_name(parameters):
# code block
return result
# CALLING a function
function_name(arguments)

Simplest Example

# Define once

def say_hello():
print("Hello, World!")

# Call anytime, anywhere
say_hello() # Hello, World!
say_hello() # Hello, World!
say_hello() # Hello, World!

Functions with Parameters (Inputs)

# One parameter

def greet(name):
print("Hello", name)

greet("Alice") # Hello Alice
greet("Bob") # Hello Bob

# Two parameters

def add(a, b):
print(a + b)
add(3, 5) # 8
add(10, 20) # 30

4 Types of Functions:

1️ No Input, No Output
2 Input, No Output
3 No Input, With Output
4 Input AND Output

1️ No Input, No Output

def say_hello():
print("Hello!")
say_hello()

2 Input, No Output

def greet(name):
print("Hello", name)
greet("Alice")

3 No Input, With Output

def get_pi():
return 3.14159
pi = get_pi()
print(pi) # 3.14159

4 Input AND Output

def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result) # 20

# Why we use functions?

To avoid repeating the same code again and again.

# Creating and calling a function

def text():
print("Hello Welcome to python Functions")
text()
text()

a = 3
b = 5
multiplication = a*b
print(multiplication)

a = 11
b = 15
multiplication = a*b
print(multiplication)

a = 20
b = 35

multiplication = a*b
print(multiplication)'''

# funtion with parameters

def multiplication(a, b):
print(a * b)
multiplication(6, 7)
multiplication(55, 60)'''

def addition(q, r):
print(q + r)
addition(20, 35)
addition(3500, 3223)
addition(25,45)'

def greet_user(name):
print(f"Hello {name} Glad To Meet You!")
greet_user("Qader")
greet_user("Lubna")
greet_user("Shoaib")
greet_user("Rumaysa")'''

#creating and calling a function (without parameters)

def text():
print("Hello Qader Welcome To Python Funtions!")
text()

#creating and calling a function (with parameters)

def multiplication(a,b):
print(a * b)
multiplication(5, 9) # multiplication

#creating and calling a function (with parameters)

def addition(a,b):
print(a + b)
addition(15, 15) #addition

#creating and calling a function (with parameters)

def division(a,b):
print(a / b)
division(20, 5) #division

#creating and calling a function (with parameters)

def substraction(a,b):
print(a - b)
substraction(35, 30) # substraction

def greet_user(name):
print(f"Hello{name} Glad to Meet You!")
greet_user("Mohammed Qadar")
greet_user("MohammedQadar")
greet_user("MQadar")
greet_user("QadarM")

-Return statement in Functions:

def add(a,b):
return a + b
result=add(5,5)
print("sum ", result)

-Default parameters in function?

Syntax:

def welcome(name= "Guest"):
print(f"welcome, {name}!")
welcome()
welcome("Qader")

Example:

def welcome(name= "khadar"):
print(f"welcome {name} great to see you!")
welcome()
welcome("qader")

# Billing system example:

def calculate_total(price, tax=0.05):
total= price + (price * tax)
return total
print(calculate_total(100))
print(calculate_total(100, 0.08))

# Keywords and Arguments in Functions?

Syntax:

def student_info(name, age):
print(f"name: {name}, age: {age}")
student_info(age=39, name="Mohammed")

# ATM System Project

def check_balance(balance):
print(f"Your current balance is rupees {balance}")

def withdraw(balance, amount):
if amount > balance:
print("Insufficient balance")
return balance
else:
balance = balance - amount
print(f"Withdraw successful & new balance: rupees {balance}")
return balance

def deposit(balance, amount):
balance = balance + amount
print(f"Deposit successful and new balance is: rupees {balance}")
return balance

def atm():
balance = 10000
print("Welcome to the ATM")

while True:
print("\nChoose option:")
print("1. Check balance")
print("2. Withdraw money")
print("3. Deposit money")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
check_balance(balance)
elif choice == "2":
amount = float(input("Enter amount to withdraw: Rupees "))
balance = withdraw(balance, amount)
elif choice == "3":
amount = float(input("Enter amount to deposit: Rupees "))
balance = deposit(balance, amount)
elif choice == "4":
print("Exit, Goodbye")
break
else:
print("Invalid choice")
atm()

# Mini project on calculator:

def add(x, y):
return x + y
def subtraction(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Cannot divide zero"
return x / y
print("Addition:", add(3, 6))
print("Subtraction:", subtraction(8, 5))
print("Multiplication:", multiply(11, 3))
print("Division:", divide(10, 5))