๐ฐ What Are Lists ?

A list is an ordered collection of items stored in a single variable.
๐ Lists are defined using square brackets []
.
๐งช Example :
pythonCopierModifierfruits = ["apple", "banana", "orange"]
print(fruits)
๐ค Output:
cssCopierModifier['apple', 'banana', 'orange']
๐งฉ Key Properties of Lists:
- โ Lists can store different types of data (strings, numbers, etc.).
- โ They are mutable (you can change the content).
- โ Support looping, updating, and searching.
๐ฅ Adding Items to a List
pythonCopierModifierfruits.append("grapes")
print(fruits)
๐ข append()
adds an item to the end of the list.
โ Removing an Item from the List
pythonCopierModifierfruits.remove("banana")
print(fruits)
๐ If the item is not found, it raises an error.
๐๏ธ Accessing List Elements:
โ Using indexing:
pythonCopierModifierprint(fruits[0]) # First item
print(fruits[-1]) # Last item
๐ Looping Through a List:
pythonCopierModifierfor fruit in fruits:
print("I like", fruit)
๐ Sorting a List:
pythonCopierModifiernumbers = [5, 1, 9, 3]
numbers.sort()
print(numbers) # [1, 3, 5, 9]
๐ง Exercise 1:
Write a program that:
- Creates an empty list.
- Asks the user to enter 3 friend names.
- Adds them to the list.
- Prints the final list.
pythonCopierModifierfriends = []
for i in range(3):
name = input("Enter a friend's name: ")
friends.append(name)
print("๐ Your friends are:", friends)
๐ Useful List Functions:
Function | Purpose |
---|---|
append(x) | Add item x to the end |
remove(x) | Remove item x by value |
pop(i) | Remove item at index i |
sort() | Sort list in ascending order |
reverse() | Reverse the list order |
len(list) | Get the number of elements |
list.clear() | Remove all elements |
๐ Searching in a List:
pythonCopierModifierif "banana" in fruits:
print("๐ Banana is in the list!")
else:
print("Banana is not found.")
๐ง Exercise 2 (Intermediate):
Write a program that:
- Asks the user to enter numbers until they type “exit”.
- Stores them in a list.
- Calculates the sum and average.
- Prints the total number of entries.
pythonCopierModifiernumbers = []
while True:
entry = input("Enter a number (or type 'exit' to finish): ")
if entry.lower() == "exit":
break
try:
num = float(entry)
numbers.append(num)
except:
print("โ ๏ธ Please enter a valid number.")
if numbers:
print("๐ Count:", len(numbers))
print("๐ข Sum:", sum(numbers))
print("๐ Average:", sum(numbers) / len(numbers))
else:
print("No numbers were entered.")
๐ Summary:
- Lists are powerful for managing collections of data.
- You can add, remove, sort, reverse, and search items easily.
- Lists are used everywhere in real-world Python programs.
User: MohammedYaseenTayeb
Pass: 66259927
User: AlobaidiAlhamadi
Pass: 86129517
User: MuhammadMahmod
Pass: 63944489
User: TarekShiekhHamoud
Pass: 62855174