ЁЯФм
ЁЯзм
ЁЯФн
ЁЯкР
ЁЯзк
тЖР Back to Dashboard
Font Size:

1. Introduction

The second revision tour consolidates the compound data types and control structures of Python that are essential for the Class 12 syllabus. While the first tour covered the language's basics, this tour focuses on strings, lists, tuples, dictionaries and sets, together with the conditional and looping statements that drive programs. These collections appear in nearly every chapter that follows, from stacks and queues implemented with lists to the processing of data tables represented as lists of dictionaries.

A sequence in Python is an ordered collection of elements supporting indexing, slicing and iteration. Strings, lists and tuples are all sequences. Dictionaries and sets, while also collections, differ: dictionaries map keys to values, and sets store unordered unique elements. Control structures, the if family and the while and for loops, operate on these collections to make decisions and repeat work.

This chapter revises each type with its key methods and operations, covers the two loop statements with break, continue and the loop-else clause, and includes the sorted, reversed, min, max, sum and enumerate built-in functions. Accurate recall of method names and their exact behaviour is essential, since questions in the examination frequently ask for the output of short programs using these operations.

2. Strings

A string is an immutable sequence of characters enclosed in single, double or triple quotes. Strings support indexing from 0, negative indexing from the end, slicing with [start:stop:step], and a rich set of methods.

word = "Python"
print(word[0])       # P
print(word[-1])      # n
print(word[1:4])     # yth
print(word[::-1])    # nohtyP

2.1 Common String Methods

text = "  Hello World  "
print(text.strip())            # Hello World
parts = "A,B,C".split(",")
print(parts)                   # ['A', 'B', 'C']
print("-".join(parts))         # A-B-C
print(text.lower().strip())    # hello world

2.2 String Immutability

Strings cannot be modified in place. Expressions like word[0] = "J" raise a TypeError. To change a string, a new string is built, usually by slicing.

word = "Python"
new_word = "J" + word[1:]
print(new_word)    # Jython

3. Lists

A list is a mutable, ordered sequence of elements enclosed in square brackets. Elements can be of mixed types, and a list can contain other collections. Lists support indexing, slicing, concatenation and repetition, and provide methods for modifying content.

lst = [10, 20, 30, 40]
lst.append(50)          # add at the end
lst.insert(1, 15)       # insert at index 1
lst.remove(30)          # remove first occurrence of 30
print(lst)              # [10, 15, 20, 40, 50]
popped = lst.pop()      # remove and return last element
print(popped)           # 50

3.1 Common List Methods

nums = [3, 1, 4, 1, 5]
nums.sort()
print(nums)          # [1, 1, 3, 4, 5]
print(nums.count(1)) # 2

3.2 List Slicing

Slicing returns a new list. lst[start:stop] includes start, excludes stop; lst[:] copies the whole list; lst[::-1] reverses it.

lst = [0, 1, 2, 3, 4, 5]
print(lst[1:4])      # [1, 2, 3]
print(lst[::2])      # [0, 2, 4]

4. Tuples

A tuple is an immutable sequence enclosed in parentheses. Tuples are faster and protect data from accidental modification. A single-element tuple needs a trailing comma, like (5,). Since tuples are immutable, they have no append, insert or remove methods; they support indexing, slicing, concatenation and the count() and index() methods.

t = (10, 20, 30)
print(t[1])          # 20
print(t[:2])         # (10, 20)
a, b, c = t          # tuple unpacking
print(a, b, c)       # 10 20 30

Tuple unpacking assigns each element to a variable in order, a common Python idiom.

5. Dictionaries

A dictionary stores key-value pairs in braces. Keys must be immutable (strings, numbers, tuples) and unique; values may be of any type. Dictionaries are mutable and unordered in older Python, though modern Python preserves insertion order.

student = {"roll": 1, "name": "Aarav", "marks": 92}
print(student["name"])          # Aarav
student["marks"] = 95           # update value
student["city"] = "Delhi"       # add new key
print(student.get("grade", "NA"))  # NA (default)
del student["city"]
print(len(student))             # 3

5.1 Dictionary Methods

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

6. Sets

A set is an unordered collection of unique elements enclosed in braces. Duplicate elements are automatically removed. Sets support mathematical operations: union (|), intersection (&), difference (-) and symmetric difference (^), plus methods like add(), remove() and discard().

a = {1, 2, 3, 3}
print(a)              # {1, 2, 3}
b = {3, 4, 5}
print(a | b)          # {1, 2, 3, 4, 5}
print(a & b)          # {3}
print(a - b)          # {1, 2}

Since sets are unordered, they do not support indexing or slicing.

7. Control Structures

7.1 The if Family

The if, if-else and if-elif-else statements make decisions. Only the block of the first true condition executes; the else block is optional and runs when no condition holds.

marks = 85
if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
else:
    grade = "C"
print("Grade:", grade)   # Grade: B

7.2 The for Loop

The for loop iterates over any sequence or iterable, most commonly range(), a list, a string, a dictionary's keys, or the enumerate() function.

for i in range(5):
    print(i, end=" ")     # 0 1 2 3 4

for index, value in enumerate(["a", "b", "c"]):
    print(index, value)   # 0 a 1 b 2 c

7.3 The while Loop

The while loop repeats while its condition is true. The loop control variable must be updated inside the body to avoid infinite loops.

total, n = 0, 1
while n <= 5:
    total += n
    n += 1
print(total)      # 15

7.4 break, continue and the Loop-else Clause

break exits the loop immediately. continue skips the rest of the current iteration. The else clause of a loop runs only when the loop finishes normally without break.

for n in range(2, 20):
    if n % 3 == 0:
        print("First multiple of 3:", n)
        break
else:
    print("No multiple of 3")

8. Built-in Functions for Collections

Python provides several useful built-ins. len() returns the number of elements, sum() adds numeric elements, min() and max() find extremes, sorted() returns a new sorted list, reversed() returns a reversed iterator, and enumerate() pairs elements with their indices.

marks = [85, 92, 78, 95]
print(sum(marks))          # 350
print(max(marks))          # 95
print(min(marks))          # 78
print(sorted(marks))       # [78, 85, 92, 95]
print(list(reversed(marks)))  # [95, 78, 92, 85]

Quick Revision Tables

Table 1: Sequence Types

Type Mutable? Example Key Methods
str No "Python" upper, split, join, find
list Yes [1, 2, 3] append, insert, pop, sort
tuple No (1, 2, 3) count, index
dict Yes {"a": 1} keys, values, get, items
set Yes {1, 2, 3} add, remove, union

Table 2: Loop Control Statements

Statement Effect
break Terminate the loop immediately
continue Skip the rest of the current iteration
else (with loop) Runs only if loop finishes without break

Mind Map

flowchart TD A[Python Revision Tour II] --> B[Strings] B --> B1[Immutable sequence] B --> B2[Methods: split join strip] A --> C[Lists] C --> C1[Mutable sequence] C --> C2[append insert pop sort] A --> D[Tuples] D --> D1[Immutable] D --> D2[Unpacking] A --> E[Dictionaries] E --> E1[Key-value pairs] E --> E2[keys values items get] A --> F[Sets] F --> F1[Unique unordered] F --> F2[Union intersection] A --> G[Control Structures] G --> G1[if elif else] G --> G2[for and while] G --> G3[break continue loop-else] A --> H[Built-in Functions] H --> H1[sum max min sorted] H --> H2[enumerate reversed]

Important Diagrams (SVG)

Diagram 1: Collection Types Overview

Python Collection Types COLLECTIONS SEQUENCES DICTIONARIES SETS str (immutable) list (mutable) tuple (immutable) key : value pairs keys must be immutable keys values items unordered unique elements no indexing union intersection Golden Rule: Strings and tuples are immutable; lists, dictionaries and sets are mutable.

Diagram 2: Flow of a Loop with break and continue

Loop Flow: continue and break START Condition? EXIT LOOP Loop body continue? skip to next break? EXIT via break continue skips rest of iteration Golden Rule: break ends the loop; continue skips only the current iteration.

Common Mistakes

  1. Mutating a string or tuple: Assigning to an index raises TypeError; strings and tuples are immutable.
  2. Using a mutable key in a dictionary: Lists and dictionaries cannot be dictionary keys; keys must be immutable.
  3. Creating a set with an empty brace: {} creates an empty dictionary, not a set; use set() for an empty set.
  4. Forgetting the trailing comma in a one-element tuple: (5) is just the number 5; (5,) is a tuple.
  5. Using break and continue incorrectly: break exits the whole loop while continue skips only the current iteration.
  6. Expecting index order in sets: Sets are unordered, so indexing and slicing do not work.
  7. Modifying a list while iterating over it: Deleting elements during iteration skips elements; iterate over a copy instead.
  8. Confusing list slicing boundaries: lst[1:4] excludes index 4; forgetting that the stop value is exclusive causes off-by-one errors.

Exam Tips

  1. Practise slicing including negative steps; [::-1] reversing appears constantly in output questions.
  2. Memorise the mutability table and be able to justify whether a method works on a type.
  3. Know the dictionary iteration: for k in d gives keys; for k, v in d.items() gives pairs.
  4. Write clean loop traces for for and while questions, recording each output line.
  5. Remember the loop-else clause: it runs only when the loop is not terminated by break.
  6. Use tuple unpacking in code answers; it demonstrates proficiency and simplifies assignments.
  7. Revise set operations with one example each of union, intersection and difference.

Conclusion

The second revision tour completed the core toolkit of Python programming. Strings, lists, tuples, dictionaries and sets provide every common way to store and organise data, each with its own mutability, ordering and operations. Control structures give programs decision-making and repetition, with break, continue and the loop-else clause providing precise control. Built-in functions such as sum, max, min, sorted and enumerate make working with these collections concise and expressive. This knowledge is the foundation for the remaining chapters: functions and recursion build directly on these types, and the data structures of stacks and queues rely on lists. The next chapter examines functions, the mechanism by which programs are organised into reusable, manageable units.