Python 24-Day Course - Day 3: Lists

Day 3: Lists

Creating Lists and Indexing

A list is an ordered, mutable collection.

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]

print(fruits[0])    # apple
print(fruits[-1])   # cherry

Slicing

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5])    # [2, 3, 4]
print(nums[:3])     # [0, 1, 2]
print(nums[7:])     # [7, 8, 9]
print(nums[::2])    # [0, 2, 4, 6, 8]
print(nums[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Key Methods

MethodDescriptionExample
append(x)Add to endlst.append(4)
insert(i, x)Insert at positionlst.insert(0, "a")
remove(x)Remove by valuelst.remove("a")
pop(i)Remove and return by indexlst.pop(0)
sort()Sortlst.sort()
reverse()Reverselst.reverse()
index(x)Find index of valuelst.index("a")
count(x)Count occurrenceslst.count(1)

List Operations

a = [1, 2, 3]
b = [4, 5, 6]
print(a + b)        # [1, 2, 3, 4, 5, 6]
print(a * 2)        # [1, 2, 3, 1, 2, 3]
print(3 in a)       # True
print(len(a))       # 3

Today’s Exercises

  1. Take 5 numbers as input, store them in a list, and calculate the average.
  2. Create a new list with duplicate elements removed from the original list.
  3. Write a program that extracts only the common elements from two lists.

Was this article helpful?