⬅ Previous Next ➡

Lists and Tuples

Lists vs Tuples (Basics)
  • List: ordered, mutable (can change), uses []
  • Tuple: ordered, immutable (cannot change), uses ()
  • Both support indexing, slicing, iteration, and nesting.
nums_list = [10, 20, 30]
nums_tuple = (10, 20, 30)

print(nums_list)
print(nums_tuple)
Indexing in Lists and Tuples
  • Index starts from 0.
  • Negative index starts from -1 (last item).
items = ["A", "B", "C", "D"]

print(items[0])    # A
print(items[2])    # C
print(items[-1])   # D
print(items[-2])   # C
Slicing in Lists and Tuples
  • Slicing format: seq[start:stop:step]
  • stop is excluded.
nums = [1, 2, 3, 4, 5, 6]

print(nums[0:3])     # [1, 2, 3]
print(nums[2:])      # [3, 4, 5, 6]
print(nums[:4])      # [1, 2, 3, 4]
print(nums[::2])     # [1, 3, 5]
print(nums[::-1])    # reverse
Updating Lists (Mutable)
  • Lists can be updated using index or slicing.
  • Tuples cannot be updated (immutable).
nums = [10, 20, 30, 40]

nums[1] = 99
print(nums)          # [10, 99, 30, 40]

nums[2:4] = [55, 66]
print(nums)          # [10, 99, 55, 66]
List Methods (Common)
  • append(x) add at end
  • insert(i, x) add at index
  • extend(iterable) add multiple
  • remove(x) remove by value
  • pop() remove last / pop(i) by index
  • sort(), reverse()
  • count(x), index(x)
lst = [3, 1, 2]

lst.append(4)
lst.insert(1, 99)
lst.extend([5, 6])
lst.remove(99)
lst.sort()
lst.reverse()

print(lst)
Tuple Methods (Limited)
  • Tuple is immutable, so methods are limited.
  • Common methods: count(), index()
t = (10, 20, 10, 30)

print(t.count(10))     # 2
print(t.index(20))     # 1
Nested Lists
  • List inside another list is called nested list.
  • Access using two indexes: list[row][col]
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[0])       # [1, 2, 3]
print(matrix[1][2])    # 6
Iteration over Lists and Tuples
  • Use for loop to iterate items.
  • Use range() with index if needed.
nums = [10, 20, 30]

for x in nums:
    print(x)

for i in range(len(nums)):
    print(i, nums[i])
Packing and Unpacking
  • Packing: storing multiple values into one tuple/list.
  • Unpacking: extracting values into variables.
  • Use * for remaining items.
# Packing
data = 10, 20, 30
print(data)             # (10, 20, 30)

# Unpacking
a, b, c = data
print(a, b, c)

# Unpacking with *
nums = [1, 2, 3, 4, 5]
x, y, *rest = nums
print(x, y)
print(rest)
Comparison of Lists and Tuples
  • == compares values (element-wise).
  • <, > compares lexicographically (like dictionary order).
  • Comparison happens item by item from left to right.
a = [1, 2, 3]
b = [1, 2, 4]
c = [1, 2, 3]

print(a == b)    # False
print(a == c)    # True
print(a < b)     # True

t1 = (1, 5)
t2 = (1, 3)
print(t1 > t2)   # True
⬅ Previous Next ➡