🟢 Beginner · Lesson 12
Lists in Python
What is a List?
A list stores many values in one variable, in order, inside square brackets [ ]. Lists are mutable — you can add, remove and change items.
Python – list.py
marks = [85, 92, 78, 90] print(marks) print(len(marks)) # how many items
[85, 92, 78, 90]
4
Access & Slice
Python – access.py
fruits = ["apple", "banana", "mango"] print(fruits[0]) # first print(fruits[-1]) # last print(fruits[0:2]) # first two
apple
mango
['apple', 'banana']
List Methods
| Method | Does |
|---|---|
| .append(x) | add x at the end |
| .insert(i,x) | add x at position i |
| .remove(x) | delete first x |
| .pop() | remove & return last |
| .sort() | sort in place |
| .reverse() | reverse order |
| .count(x) | how many x |
Program 1: Create & Loop Through
Python – loop_list.py
names = ["Aman", "Riya", "Karan"]
for name in names:
print("Student:", name)Student: Aman
Student: Riya
Student: Karan
A for loop visits each item one by one — no index needed.
Program 2: Sum, Max and Min
Python – stats.py
marks = [85, 92, 78, 90, 88]
print("Total :", sum(marks))
print("Highest:", max(marks))
print("Lowest :", min(marks))
print("Average:", sum(marks) / len(marks))Total : 433
Highest: 92
Lowest : 78
Average: 86.6
Built-in functions sum(), max(), min(), len() work directly on lists.
Program 3: Search in a List
Python – search.py
numbers = [10, 25, 30, 45]
x = int(input("Search for: "))
if x in numbers:
print(x, "found at position", numbers.index(x))
else:
print(x, "not in list")Search for: 30
30 found at position 2
x in numberschecks membership..index(x)gives the position of the item.
Program 4: Sort & Remove Duplicates
Python – cleanup.py
data = [5, 2, 8, 2, 5, 1] data = list(set(data)) # set removes duplicates data.sort() # then sort print(data)
[1, 2, 5, 8]
set(data) drops duplicates; list() turns it back; .sort() orders it.
List Comprehension (a peek)
A short way to build lists in one line:
Python – comp.py
squares = [x*x for x in range(1, 6)] print(squares)
[1, 4, 9, 16, 25]
Common Mistakes
- Index out of range —
marks[10]on a 4-item list errors. .remove(x)errors if x is not present.- Confusing
append(one item) withextend(many items).
Practice Tasks
- Store 5 marks and print the total and average.
- Find the largest number in a list without using
max(). - Count even and odd numbers in a list.
- Remove duplicates from a list and sort it.
Summary
- Lists hold ordered, changeable items in
[ ]. - Methods: append, insert, remove, pop, sort, reverse.
sum/max/min/lenwork directly;inchecks membership.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.