Python Series track

Week 06 · Basic Track

Week 6 — Lists & Tuples

Work with Python's most-used sequence types. Master list CRUD operations, slicing syntax, common list methods, and tuple unpacking.

Basic Track3 min readFree lesson

Level: Basic | Prerequisite: Week 5 (Loops)

Learning Goals

  • Creating, indexing, and slicing lists
  • Commonly used list methods (append, pop, sort, etc.)
  • Features of tuples and unpacking
  • Differences between lists and tuples

1. Lists

A data structure that holds multiple values in order. Square brackets [...].

fruits = ["Apple", "Banana", "Grape"]
print(fruits[0])    #Apple
print(fruits[-1])   #Grapes (counting from the back)
print(len(fruits))  # 3

2. Slicing

[start:end:interval]. The end is not included.

nums = [10, 20, 30, 40, 50]
print(nums[1:4])     # [20, 30, 40]
print(nums[:3])      # [10, 20, 30]
print(nums[2:])      # [30, 40, 50]
print(nums[::-1])    #[50, 40, 30, 20, 10] (reverse order)
print(nums[::2])     # [10, 30, 50]

3. Frequently Used Methods

Method Action
append(x) Add to the end
insert(i, x) Insert at position i
pop() / pop(i) Remove and return the last / i-th element
remove(x) Remove value x
sort() Sort (in-place)
reverse() Reverse (in-place)
index(x) Position of x
count(x) Count of x
nums = [3, 1, 4, 1, 5]
nums.append(9)        # [3, 1, 4, 1, 5, 9]
nums.sort()           # [1, 1, 3, 4, 5, 9]
nums.reverse()        # [9, 5, 4, 3, 1, 1]
print(nums.count(1))  # 2

4. Iteration and enumerate

fruits = ["Apple", "Banana", "Grape"]

for fruit in fruits:
    print(fruit)

for i, fruit in enumerate(fruits, start=1):
    print(f"Number {i}: {fruit}")

5. Tuples

Similar to lists but immutable. Parentheses (...).

point = (10, 20)
x, y = point          #Unpacking
print(x, y)           # 10 20

#Tuples are immutable
# point[0] = 5         # TypeError

6. Lists vs Tuples

List Tuple
Syntax [...] (...)
Mutability Mutable Immutable
Usage Frequently changing data Fixed data (coordinates, RGB, etc.)
Speed Slow Fast

Key Examples (examples/)

File Content
01_list_basic.py Creating and indexing lists
02_slicing.py Slicing
03_methods.py append/pop/sort, etc.
04_tuple.py Tuples and unpacking

⚠️ Common Mistakes

  1. Index out of range
    a = [1, 2, 3]
    print(a[3])   # IndexError
    

→ The last is a[-1] or a[len(a)-1].

  1. Assign the return value of sort() to a variable
    sorted_list = nums.sort()   #None! No return value since it is in-place alignment
    

→ After nums.sort(), nums itself is sorted. For a new list, use sorted(nums).

  1. List copy pitfall
    a = [1, 2, 3]
    b = a          #Refers to the same list!
    b.append(4)
    print(a)       #[1, 2, 3, 4] — a also changes
    

→ To copy, use b = a.copy() or b = a[:].

  1. Creating an empty tuple () is an empty tuple. A single-item tuple is (5,) (comma required). (5) is just the integer 5.

❓ FAQ

Q1. Can different types be mixed in a list? A. Yes. [1, "hi", True, [1,2]] is possible. However, the same type is recommended.

Q2. Why is the end of a slice non-inclusive? A. range, for consistency with indices, etc. Length calculation is naturally end - start.

Q3. What is the difference between sort() and sorted()? A. sort() is a method that modifies the original. sorted() is a function that returns a new list.

📝 Exercises (exercises/)

  • exercise1.md — Student Score Statistics
  • exercise2.md — Lotto Number Generator
  • exercise3.md — List Reversal (Two Methods)

Next Week

Week 7. Dictionary and Set — Key-Value Mapping

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

examples/01_list_basic.pyPython
fruits = ["Apple", "Banana", "Grape"]
print(fruits[0])      #Apple
print(fruits[-1])     #Grapes
print(len(fruits))    # 3

#Various types possible (not recommended)
mixed = [1, "hello", True, 3.14]
print(mixed)

#Empty list
empty = []
print(len(empty))     # 0
examples/02_slicing.pyPython
nums = [10, 20, 30, 40, 50]

print(nums[1:4])      # [20, 30, 40]
print(nums[:3])       # [10, 20, 30]
print(nums[2:])       # [30, 40, 50]
print(nums[::-1])     # [50, 40, 30, 20, 10]
print(nums[::2])      # [10, 30, 50]

#Strings can also be sliced
s = "Hello"
print(s[1:4])         # ell
print(s[::-1])        # olleH
examples/03_methods.pyPython
nums = [3, 1, 4, 1, 5, 9, 2, 6]

nums.append(10)
print("append:", nums)

nums.insert(0, 0)
print("insert:", nums)

last = nums.pop()
print("pop:", last, nums)

nums.remove(1)
print("remove(1):", nums)

nums.sort()
print("sort:", nums)

nums.reverse()
print("reverse:", nums)

print("count(2):", nums.count(2))
print("index(5):", nums.index(5))
examples/04_tuple.pyPython
#Tuple
point = (10, 20)
x, y = point
print(x, y)

#Use tuples when a function returns multiple values
def min_max(nums):
    return min(nums), max(nums)

lo, hi = min_max([3, 1, 4, 1, 5])
print(lo, hi)

#Single-item tuple
single = (5,)
print(single, type(single))

#Tuples are immutable
try:
    point[0] = 99
except TypeError as e:
    print("Error:", e)

Assignment

Goal

Store the scores of 5 students in a list and print the statistics.

Requirements

  • Receive the scores of 5 students and store them in a list
  • Print total score, average, highest score, lowest score

Input/Output Example

Student 1 Score: 85
Student 2 Score: 92
Student 3 Score: 78
Student 4 Score: 88
Student 5 Score: 95

Total Score: 438
Average: 87.6
Highest Score: 95
Lowest Score: 78

Assignment 2. Lotto Number Generator

Goal

Select 6 numbers from 1 to 45 without duplicates, sort them, and print.

Requirements

  • random.sample can be used
  • Result should be sorted in ascending order

Input/Output Example

This week's lotto numbers: [3, 14, 22, 28, 35, 41]

Challenge

  • Print 5 games at once

Assignment 3. List Reversal (Two Methods)

Goal

Implement the same result using slicing and reverse() methods.

Requirements

  • Reverse an arbitrary list (e.g., [1, 2, 3, 4, 5])
  • Method 1: Slicing [::-1] (keep original, new list)
  • Method 2: .reverse() (in place)
  • Print both results

Input/Output Example

Original: [1, 2, 3, 4, 5]
Method 1 (slicing): [5, 4, 3, 2, 1]
Method 2 (reverse): [5, 4, 3, 2, 1]
As original: [5, 4, 3, 2, 1]   # after reverse applied
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution1.pyPython
scores = []
for i in range(1, 6):
    s = int(input(f"Student {i} score:"))
    scores.append(s)

total = sum(scores)
avg = total / len(scores)
print(f"Total: {total}")
print(f"Average: {avg:.1f}")
print(f"Highest score: {max(scores)}")
print(f"Lowest score: {min(scores)}")
solution2.pyPython
import random

numbers = sorted(random.sample(range(1, 46), 6))
print(f"This week's lottery numbers: {numbers}")
solution3.pyPython
nums = [1, 2, 3, 4, 5]
print(f"Original: {nums}")

reversed1 = nums[::-1]   #New List
print(f"Method 1 (Slicing): {reversed1}")

nums.reverse()           #Original Position
print(f"Method 2 (reverse): {nums}")
print(f"Original also changed: {nums}")

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now