Python Tutorial menu

Python Lists

A list stores many values in one variable, in a fixed order.

Creating a List

Write the items inside square brackets [], separated by commas:

Example

python
fruits = ["mango", "banana", "apple"]
marks = [78, 92, 65, 88]
mixed = ["Ali", 19, True]
print(fruits)
print(len(marks))
Output
['mango', 'banana', 'apple']
4

Lists are ordered (items keep their position), changeable, and they allow duplicates.

Accessing Items

Like strings, list items have index numbers starting at 0:

Example

python
fruits = ["mango", "banana", "apple", "guava"]
print(fruits[0])
print(fruits[-1])
print(fruits[1:3])
Output
mango
guava
['banana', 'apple']

Changing Items

Example

python
fruits = ["mango", "banana", "apple"]
fruits[1] = "orange"
print(fruits)
Output
['mango', 'orange', 'apple']

Adding and Removing Items

Example

python
cart = ["rice", "sugar"]
cart.append("tea")          # add at the end
cart.insert(0, "flour")     # add at position 0
print(cart)

cart.remove("sugar")        # remove by value
last = cart.pop()           # remove and return the last item
print(cart)
print("Removed:", last)
Output
['flour', 'rice', 'sugar', 'tea']
['flour', 'rice']
Removed: tea
MethodWhat it does
append(x)Adds x at the end
insert(i, x)Adds x at index i
extend(other)Adds all items of another list
remove(x)Removes the first x
pop(i)Removes item at index i (last one if empty)
clear()Removes all items
index(x)Position of x
count(x)How many times x appears

Sorting

Example

python
marks = [78, 92, 65, 88]
marks.sort()
print(marks)
marks.sort(reverse=True)
print(marks)

names = ["Zara", "ali", "Bilal"]
print(sorted(names, key=str.lower))
Output
[65, 78, 88, 92]
[92, 88, 78, 65]
['ali', 'Bilal', 'Zara']

sort() changes the list itself. sorted() gives back a new sorted list and leaves the original alone.

Looping Through a List

Example

python
subjects = ["Maths", "Physics", "English"]
for s in subjects:
    print("I study", s)
Output
I study Maths
I study Physics
I study English

Copying a List

Writing b = a does not copy a list. Both names point to the same list, so changing one changes the other. Use b = a.copy() to make a real copy.

List Comprehension

A list comprehension builds a new list in one short line:

Example

python
prices = [100, 250, 400]
with_tax = [p * 1.18 for p in prices]
print(with_tax)

marks = [45, 78, 32, 90]
passed = [m for m in marks if m >= 50]
print(passed)
Output
[118.0, 295.0, 472.0]
[78, 90]

Read it as: "give me p * 1.18 for every p in prices".

Exercise

Exercise

Which method adds an item to the end of a list?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp