MODULE 03

Python Data Structures

Master Lists, Tuples, Sets and Dictionaries from the basics to practical programming. Every topic is explained step by step with examples, common mistakes, coding practice and theory questions.

4Core Structures
30Coding Questions
30Theory Q&A
Step-by-StepTeaching Style

Module Contents

1. Lists2. Tuples3. Sets4. Dictionaries5. Comparison & SelectionCoding PracticeTheory Q&A

1. Lists

A list stores multiple values in one variable. Lists are ordered, changeable (mutable), and allow duplicate values. They are one of the most commonly used Python data structures.

1.1 Creating a List

Use square brackets [] and separate elements with commas.

marks = [85, 90, 78, 92]
names = ["Ravi", "Anu", "Kiran"]
mixed = [10, "Python", 3.5, True]
Step by step:
  1. Python creates a list object.
  2. Each element is stored in sequence.
  3. The variable points to that list.

1.2 Indexing

Indexing gets one element. Python starts counting from 0.

colors = ["red", "green", "blue", "yellow"]

print(colors[0])   # red
print(colors[2])   # blue
print(colors[-1])  # yellow
print(colors[-2])  # blue

Positive indexes move from the beginning; negative indexes move from the end.

1.3 Slicing

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[1:4])   # [20, 30, 40]
print(numbers[:3])    # [10, 20, 30]
print(numbers[3:])    # [40, 50, 60]
print(numbers[::2])   # [10, 30, 50]
print(numbers[::-1])  # reverse copy

The general form is list[start:stop:step]. The stop position is excluded.

1.4 Updating List Elements

marks = [70, 80, 90]
marks[1] = 95
print(marks)  # [70, 95, 90]

Because lists are mutable, existing elements can be changed.

1.5 Adding Elements

append()

items = [10, 20]
items.append(30)
print(items)  # [10, 20, 30]

extend()

items = [10, 20]
items.extend([30, 40])
print(items)  # [10, 20, 30, 40]

insert()

items = [10, 30]
items.insert(1, 20)
print(items)  # [10, 20, 30]

append() adds one object at the end, extend() adds elements from an iterable, and insert() adds at a chosen index.

1.6 Removing Elements

items = ["A", "B", "C", "D"]

items.remove("B")  # removes first matching value
x = items.pop()    # removes and returns last element
y = items.pop(0)   # removes and returns index 0
del items[0]       # deletes by index
items.clear()      # removes everything
Remember: remove() uses a value; pop() uses an index and returns the removed item; del deletes by index or slice.

1.7 Searching, Length and Membership

names = ["Ravi", "Anu", "Kiran"]

print(len(names))
print("Anu" in names)
print(names.index("Kiran"))
print(names.count("Ravi"))

1.8 Looping Through a List

marks = [80, 90, 75]

for mark in marks:
    print(mark)

The loop visits each element one by one.

1.9 Sorting and Reversing

numbers = [40, 10, 30, 20]

numbers.sort()
print(numbers)        # [10, 20, 30, 40]

numbers.sort(reverse=True)
print(numbers)        # [40, 30, 20, 10]

new_list = sorted(numbers)
reversed_list = list(reversed(numbers))

sort() changes the original list. sorted() returns a new sorted list.

1.10 Copy vs Alias

a = [1, 2, 3]
b = a
b.append(4)

print(a)  # [1, 2, 3, 4]

b = a creates another reference to the same list. Use a.copy() for a shallow copy.

a = [1, 2, 3]
b = a.copy()
b.append(4)

print(a)  # [1, 2, 3]
print(b)  # [1, 2, 3, 4]

1.11 List Comprehension

squares = [x * x for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

evens = [x for x in range(1, 11) if x % 2 == 0]

List comprehensions provide a compact way to build lists from an iterable.

1.12 Nested Lists

students = [
    ["Ravi", 85],
    ["Anu", 92],
    ["Kiran", 78]
]

print(students[0][0])  # Ravi
print(students[1][1])  # 92

A nested list contains other lists. Use multiple indexes to reach inner elements.

2. Tuples

A tuple is an ordered collection that cannot be changed after creation. Tuples are useful when data should remain fixed.

2.1 Creating Tuples

point = (10, 20)
colors = ("red", "green", "blue")
empty = ()

single = (10,)   # comma is important

(10) is just the integer 10. (10,) is a one-element tuple.

2.2 Indexing and Slicing

data = ("A", "B", "C", "D")

print(data[0])
print(data[-1])
print(data[1:3])

2.3 Tuple Immutability

numbers = (10, 20, 30)
# numbers[1] = 99  # TypeError

You cannot directly replace, append or remove tuple elements.

2.4 Tuple Packing and Unpacking

# Packing
student = "Ravi", 22, "Python"

# Unpacking
name, age, course = student

print(name)
print(age)
print(course)

Unpacking assigns tuple elements to multiple variables in one statement.

2.5 Tuple Methods

values = (10, 20, 10, 30, 10)

print(values.count(10))
print(values.index(30))

Tuples mainly provide count() and index().

2.6 Tuple vs List

ListTuple
MutableImmutable
[]()
Good for changing dataGood for fixed data

3. Sets

A set is a collection of unique elements. It is useful for removing duplicates and performing mathematical set operations.

3.1 Creating a Set

numbers = {10, 20, 30, 20, 10}
print(numbers)  # duplicates are removed

empty_set = set()
empty_dict = {}  # this is a dictionary, not a set

Do not use {} for an empty set; use set().

3.2 Adding and Updating

colors = {"red", "blue"}

colors.add("green")
colors.update(["yellow", "black"])

print(colors)

3.3 Removing Elements

colors = {"red", "blue", "green"}

colors.remove("blue")   # error if missing
colors.discard("black") # no error if missing
item = colors.pop()     # removes an arbitrary set element
colors.clear()

3.4 Membership

skills = {"Python", "SQL", "Power BI"}

print("Python" in skills)
print("Java" not in skills)

3.5 Union and Intersection

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)  # union
print(a & b)  # intersection

Union contains values from both sets. Intersection contains only common values.

3.6 Difference and Symmetric Difference

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a - b)  # only in a
print(b - a)  # only in b
print(a ^ b)  # in either set, but not both

3.7 Subset, Superset and Disjoint

a = {1, 2}
b = {1, 2, 3, 4}

print(a.issubset(b))
print(b.issuperset(a))
print(a.isdisjoint({7, 8}))

3.8 Frozenset

fixed = frozenset([1, 2, 3])
# fixed.add(4)  # not allowed

A frozenset is an immutable set.

4. Dictionaries

A dictionary stores data as key-value pairs. Keys are unique and are used to retrieve values.

4.1 Creating a Dictionary

student = {
    "name": "Ravi",
    "age": 22,
    "course": "Python"
}

4.2 Accessing Values

print(student["name"])
print(student.get("age"))
print(student.get("phone", "Not available"))

dict[key] raises KeyError for a missing key, while get() can return a default value.

4.3 Adding and Updating

student["city"] = "Hyderabad"
student["age"] = 23

student.update({"course": "Data Analytics", "score": 90})

4.4 Removing Items

student = {"name": "Ravi", "age": 22, "city": "Hyderabad"}

age = student.pop("age")
last = student.popitem()
del student["name"]
student.clear()

4.5 keys(), values() and items()

student = {"name": "Ravi", "age": 22}

print(student.keys())
print(student.values())
print(student.items())

4.6 Looping Through a Dictionary

student = {"name": "Ravi", "age": 22}

for key in student:
    print(key)

for key, value in student.items():
    print(key, value)

4.7 Dictionary Membership

student = {"name": "Ravi", "age": 22}

print("name" in student)
print("Ravi" in student)  # checks keys, not values

4.8 Nested Dictionaries

students = {
    "S101": {"name": "Ravi", "marks": 85},
    "S102": {"name": "Anu", "marks": 92}
}

print(students["S102"]["marks"])

4.9 setdefault()

data = {"name": "Ravi"}
data.setdefault("city", "Hyderabad")
data.setdefault("name", "Anu")

print(data)

setdefault() inserts a key only when it does not already exist.

4.10 Dictionary Comprehension

squares = {x: x * x for x in range(1, 6)}
print(squares)

5. Choosing the Right Data Structure

StructureOrderedMutableDuplicatesIndexingBest use
ListYesYesYesYesChanging ordered collection
TupleYesNoYesYesFixed ordered data
SetNo guaranteed sequence orderYesNoNoUnique values and set operations
DictionaryInsertion-orderedYesKeys uniqueBy keyKey-value data

5.1 Practical Selection Rule

5.2 Common Mistakes

5.3 Dry-Run Example

numbers = [10, 20, 30]
numbers.append(40)
numbers[1] = 25
numbers.pop(0)

print(numbers)
Trace it:
  1. Start: [10, 20, 30]
  2. append(40): [10, 20, 30, 40]
  3. index 1 becomes 25: [10, 25, 30, 40]
  4. pop(0) removes 10: [25, 30, 40]

30 Coding Questions — Step-by-Step Solutions

Try each question yourself first. Then click the solution button to reveal the explanation and code.

01
Create and access a list

Create a list of five fruits and print the first and last fruit.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
fruits = ["apple", "banana", "mango", "orange", "grapes"]
print(fruits[0])
print(fruits[-1])
02
Positive and negative indexing

Print the second and second-last element of a list.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30, 40, 50]
print(numbers[1])
print(numbers[-2])
03
List slicing

Print the first three, last two and alternate elements.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[:3])
print(numbers[-2:])
print(numbers[::2])
04
Update a list

Change the second element of a list to 99.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30]
numbers[1] = 99
print(numbers)
05
append()

Add 40 to the end of [10, 20, 30].

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30]
numbers.append(40)
print(numbers)
06
extend()

Add [40, 50] to an existing list.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30]
numbers.extend([40, 50])
print(numbers)
07
insert()

Insert 25 between 20 and 30.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30]
numbers.insert(2, 25)
print(numbers)
08
remove()

Remove the value 20 from a list.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30, 20]
numbers.remove(20)
print(numbers)
09
pop()

Remove and print the last element.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30]
removed = numbers.pop()
print("Removed:", removed)
print(numbers)
10
List statistics

Find sum, maximum and minimum of a list.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 25, 7, 40, 18]
print("Sum:", sum(numbers))
print("Max:", max(numbers))
print("Min:", min(numbers))
11
Count occurrences

Count how many times 10 appears.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 10, 30, 10]
print(numbers.count(10))
12
Sort a list

Sort a list in ascending and descending order.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [40, 10, 30, 20]
numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)
13
Reverse a list

Reverse a list using reverse().

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)
14
Copy a list

Create a separate copy and modify only the copy.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
a = [1, 2, 3]
b = a.copy()
b.append(4)
print("a:", a)
print("b:", b)
15
List comprehension

Create squares from 1 to 10 using comprehension.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
squares = [x * x for x in range(1, 11)]
print(squares)
16
Nested list

Access the marks of the second student.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
students = [["Ravi", 85], ["Anu", 92], ["Kiran", 78]]
print(students[1][1])
17
Create a tuple

Create a tuple of three cities and print the last city.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
cities = ("Hyderabad", "Chennai", "Bengaluru")
print(cities[-1])
18
Single-element tuple

Create a tuple containing only 10.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
value = (10,)
print(value)
print(type(value))
19
Tuple unpacking

Unpack a tuple containing name, age and course.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
student = ("Ravi", 22, "Python")
name, age, course = student
print(name, age, course)
20
Tuple count and index

Count 10 and find the index of 30.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
values = (10, 20, 10, 30, 10)
print(values.count(10))
print(values.index(30))
21
Convert list to tuple

Convert a list into a tuple.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 30]
numbers_tuple = tuple(numbers)
print(numbers_tuple)
22
Remove duplicates

Remove duplicates from a list using a set.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
numbers = [10, 20, 10, 30, 20, 40]
unique = set(numbers)
print(unique)
23
Set add and update

Add one value and multiple values to a set.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
skills = {"Python", "SQL"}
skills.add("Excel")
skills.update(["Power BI", "Git"])
print(skills)
24
Set union and intersection

Find union and common elements of two sets.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Union:", a | b)
print("Intersection:", a & b)
25
Set difference

Find values that exist only in the first set.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a - b)
26
Subset and superset

Check whether {1,2} is a subset of {1,2,3}.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b))
print(b.issuperset(a))
27
Dictionary access

Create a student dictionary and safely read a missing key.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
student = {"name": "Ravi", "age": 22}
print(student["name"])
print(student.get("phone", "Not available"))
28
Dictionary add/update

Add city and update age.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
student = {"name": "Ravi", "age": 22}
student["city"] = "Hyderabad"
student["age"] = 23
print(student)
29
Dictionary iteration

Print every key and value.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
student = {"name": "Ravi", "age": 22, "course": "Python"}
for key, value in student.items():
    print(key, ":", value)
30
Nested dictionary

Access the marks of student S102.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
students = {
    "S101": {"name": "Ravi", "marks": 85},
    "S102": {"name": "Anu", "marks": 92}
}
print(students["S102"]["marks"])
31
Dictionary comprehension

Create a dictionary of numbers and their cubes.

  1. Read the requirement and identify the required data structure.
  2. Create the structure with the correct Python syntax.
  3. Perform the required operation.
  4. Print or inspect the result.
cubes = {x: x**3 for x in range(1, 6)}
print(cubes)

30 Theory Questions with Answers

Use these for revision, exams and interviews.

A data structure is a way of organizing and storing data so it can be accessed and manipulated efficiently.
A list is an ordered, mutable collection written with square brackets.
Yes. A list can contain the same value multiple times.
Indexing retrieves an element using its position. Python uses zero-based indexing.
Negative indexes access elements from the end; -1 is the last element.
Slicing extracts a range using the form start:stop:step, with stop excluded.
append() adds one object as one element; extend() adds elements from an iterable.
remove() deletes the first matching value; pop() removes by index and returns the removed item.
sort() modifies the list in place; sorted() returns a new sorted result.
An alias is another reference to the same list, such as b = a.
A list containing other lists is called a nested list.
It is a compact syntax for creating a list from an iterable, optionally with a condition.
A tuple is an ordered, immutable collection, usually written with parentheses.
Their elements cannot be reassigned, added or removed after the tuple is created.
Use a trailing comma, such as (10,).
Packing combines multiple values into a tuple, such as point = 10, 20.
Unpacking assigns tuple elements to multiple variables.
The commonly used tuple methods are count() and index().
A set is a mutable collection of unique elements used for membership and set operations.
No. Duplicate values collapse into a single set element.
Use set(); {} creates an empty dictionary.
It adds one element to a set.
It adds elements from one or more iterables to a set.
remove() raises an error if the element is absent; discard() does not.
Union combines all unique elements from two sets.
Intersection contains only elements common to both sets.
A - B contains elements present in A but not in B.
A dictionary stores key-value pairs and uses keys to retrieve values.
Keys must be unique; assigning an existing key replaces its value.
dict[key] raises KeyError when the key is missing; get() can return a default instead.
It is a compact way to create dictionaries from an iterable, such as {x: x*x for x in range(5)}.