[Go to site: main page, start]

0% found this document useful (0 votes)
2 views10 pages

Chapter2 Python ShortNotes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Chapter2 Python ShortNotes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 2 — PYTHON REVISION TOUR II

Board + CUET Last Minute Revision Notes


Sumita Arora | Class XII Computer Science

■ QUICK SUMMARY
String IMMUTABLE • Characters only • " " or ' '

List MUTABLE • Any data type • [ ] • Can grow/shrink

Tuple IMMUTABLE • Any data type • ( ) • Faster than list

Dictionary MUTABLE • Key:Value pairs • { } • Unordered • Keys must be unique & immutable

2.2 STRINGS
Definition: Sequence of characters stored in contiguous memory with two-way indexing.

Indexing
Direction Index values Example for "PYTHON"
Forward 0, 1, 2 ... length-1 P=0, Y=1, T=2, H=3, O=4, N=5

Backward -1, -2 ... -length N=-1, O=-2, H=-3, T=-4, Y=-5, P=-6

Key Points
• Strings are IMMUTABLE — individual characters CANNOT be changed
• name[0] = 'p' → gives TypeError
• Index out of bounds directly → IndexError
• Index out of bounds in slicing → NO ERROR, returns empty string

String Operators
Operator Name Rule / Example
+ Concatenation Both operands must be strings → "hello"+"world"

* Replication One string + one integer → "ha"*3 = "hahaha"

in / not in Membership Returns True/False → "a" in "apple" = True

<, >, ==, != Comparison Based on ASCII/Unicode (lexicographical order)

String Slicing → s[start : stop : step]


Syntax Meaning Example (s="PYTHON")
s[n:m] Characters from index n to m-1 s[1:4] = "YTH"

s[:n] Beginning to n-1 s[:3] = "PYT"

s[n:] From n to end s[3:] = "HON"

s[::-1] Reverse the string s[::-1] = "NOHTYP"

s[::2] Every 2nd character s[::2] = "PTO"

String Methods
Method Returns Key Point
capitalize() First char upper, rest lower Changes ALL chars
upper() All uppercase copy Original unchanged

lower() All lowercase copy Original unchanged

isalpha() True if all alphabets Digits/spaces make it False

isdigit() True if all digits Letters make it False

isalnum() True if alphabets or digits False if space/special char

isspace() True if only spaces Empty string → False

isupper() True if all uppercase Needs at least one cased char

islower() True if all lowercase Needs at least one cased char

find(sub) Lowest index, -1 if not found Returns -1 (not error) if absent

lstrip(chars) Copy with leading chars removed Default removes spaces

rstrip(chars) Copy with trailing chars removed Default removes spaces


2.3 LISTS
Definition: Mutable sequence that stores elements of any data type.
Syntax: L = [1, 2, 3] or L = [] (empty) or L = list()

Key Points
• Lists are MUTABLE — L[i] = value is VALID
• Two-way indexing — same as strings
• Slicing — same as strings; slice is a list in itself
• + joins two lists | * repeats a list

List Methods — Complete Reference


Method Syntax Returns Does
index() [Link](item) Index (int) First occurrence index; ValueError if absent

append() [Link](item) None Adds SINGLE item at END

extend() [Link](list) None Adds ALL items of list2 at end

insert() [Link](pos, item) None Inserts item before given position

pop() [Link](index) Removed item Removes & returns item; default = last

remove() [Link](value) None Removes FIRST occurrence; ValueError if absent

clear() [Link]() None Removes ALL elements; empty list remains

count() [Link](item) Count (int) Counts occurrences; returns 0 if absent

reverse() [Link]() None Reverses list IN PLACE

sort() [Link]() None Sorts in ascending order IN PLACE


Memory Trick: I A E I P R C R S → Index, Append, Extend, Insert, Pop, Remove, Clear, Reverse, Sort

append() vs extend() — VERY COMMON BOARD QUESTION


Feature append() extend()
Adds ONE single item ALL elements of another list

If list given Nested list created Flat list created

Example [Link]([4,5]) → [1,2,3,[4,5]] [Link]([4,5]) → [1,2,3,4,5]

pop() vs remove() — KEY DIFFERENCE


Feature pop() remove()
Argument Index (optional) Value (required)

Returns The removed element Nothing (None)

Default Removes last element No default

Error if not found IndexError if list empty ValueError

Shallow Copy vs Deep Copy — COMMON BOARD QUESTION


Feature Shallow Copy (b = a) Deep Copy (b = list(a))
Memory Same location Different location

Independence No — linked Yes — independent

Change in one affects other? YES NO

Other methods — b = a[:] or b = [Link]()


2.4 TUPLES
Definition: Immutable sequence — once created CANNOT be changed.
Syntax: T = (1, 2, 3) or T = () (empty) or T = tuple()

Key Points
• Tuples are IMMUTABLE — T[i] = value gives TypeError
• Single element tuple: T = (5,) — the comma is COMPULSORY
• T = (5) → this is just an INTEGER, NOT a tuple
• Two-way indexing and slicing — same as lists
• tpl + (3) → TypeError — use tpl + (3,)

Tuple vs List — Complete Comparison


Feature List Tuple
Brackets [ ] square ( ) round

Mutable YES NO

Item assignment Allowed NOT allowed

Speed Slower Faster (immutable)

Can grow/shrink YES NO

Methods available Many (sort, append etc.) Only index(), count()

Use case Data that changes Fixed/constant data

Memory More Less

Packing & Unpacking


• Packing: t = 1, 2, 3 → creates tuple (1, 2, 3)
• Unpacking: a, b, c = t → a=1, b=2, c=3
• Number of variables on left must match number of elements in tuple

Tuple Methods Reference


Method Returns Notes
len(T) Count of elements Same as list

max(T) Maximum value Elements must be same type

min(T) Minimum value Elements must be same type

[Link](item) Index of first match ValueError if not found

[Link](item) Count of item 0 if not found

tuple(seq) New tuple from sequence Works with string, list, tuple
2.5 DICTIONARIES
Definition: Mutable, unordered collection of key : value pairs.
Syntax: d = {key1 : value1, key2 : value2, ...}

Key Properties
Property Meaning
Mutable Values can be changed

Unordered No fixed order — keys are indexed not positions

Key-Value pairs Every element = key + value

Keys must be unique Duplicate keys NOT allowed

Keys must be immutable string, int, tuple can be keys — NOT lists

Accessing, Adding, Updating, Deleting


• Access: d["key"] → returns value | wrong key → KeyError
• Safe Access: [Link]("key") → returns None instead of error
• Add new key: d[new_key] = value → key must NOT exist
• Update existing: d[existing_key] = value → key must exist
• Delete: del d[key] → KeyError if key absent
• Delete & return: [Link](key) → KeyError if absent (use [Link](key, default) to avoid)
• Check key exists: "key" in d → True/False (checks KEYS only, not values)

del d vs [Link]() — COMMON BOARD QUESTION


Feature del d [Link]()
What is deleted ENTIRE dictionary object Only the elements inside

Dictionary after Does NOT exist anymore Exists as empty dict {}

Use d after this? NameError Yes — d = {}

Dictionary Methods — Complete Reference


Method Syntax Returns Does
len() len(d) Count (int) Number of key:value pairs

clear() [Link]() None Removes all items; empty dict remains

get() [Link](key, default) Value or default Safe access — no KeyError

items() [Link]() List of tuples All (key, value) pairs

keys() [Link]() List of keys All keys

values() [Link]() List of values All values

update() [Link](d2) None Merges d2 into d; overrides same keys

pop() [Link](key) Removed value Removes & returns value


2.6 SORTING TECHNIQUES

Bubble Sort
• Compares adjacent elements and swaps if not in order
• After each pass, the largest unsorted element settles at correct position
• n-1 passes needed for n elements
• In place sorting — no extra list needed
for i in range(n):
for j in range(0, n-i-1): # n-i-1 avoids rechecking sorted elements
if a[j] > a[j+1]: # swap condition
a[j], a[j+1] = a[j+1], a[j]

Bubble Sort — Dry Run on [5, 3, 8, 1]


Pass Comparisons & Swaps List after pass
Pass 1 (i=0) 5>3? Swap | 5>8? No | 8>1? Swap [3, 5, 1, 8]

Pass 2 (i=1) 3>5? No | 5>1? Swap [3, 1, 5, 8]

Pass 3 (i=2) 3>1? Swap [1, 3, 5, 8] ✓ SORTED

Insertion Sort
• Picks each element one by one from unsorted part
• Inserts it at the correct position in the already sorted part
• Builds sorted list one element at a time
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and key < a[j]: # shift elements right
a[j+1] = a[j]
j -= 1
a[j+1] = key # insert at correct position

Bubble Sort vs Insertion Sort


Feature Bubble Sort Insertion Sort
Method Compare & swap adjacent Insert in correct position

How it works Heaviest element bubbles up Builds sorted list one by one

Swaps More swaps Fewer swaps

Time Complexity O(n²) O(n²)

In place Yes Yes


SIMILARITIES — String, List, Tuple, Dictionary
Feature String List Tuple Dictionary
Indexing ✓ Yes ✓ Yes ✓ Yes ✗ No (key-based)

Slicing ✓ Yes ✓ Yes ✓ Yes ✗ No

len() ✓ Yes ✓ Yes ✓ Yes ✓ Yes

in / not in ✓ Yes ✓ Yes ✓ Yes ✓ Yes (keys only)

for loop traversal ✓ Yes ✓ Yes ✓ Yes ✓ Yes

Concatenation (+) ✓ Yes ✓ Yes ✓ Yes ✗ No

Replication (*) ✓ Yes ✓ Yes ✓ Yes ✗ No

Iterable ✓ Yes ✓ Yes ✓ Yes ✓ Yes

DIFFERENCES — String, List, Tuple, Dictionary


Feature String List Tuple Dictionary
Mutability Immutable Mutable Immutable Mutable

Syntax " " or ' ' [] () { key:val }

Stores Chars only Any type Any type Key-Value pairs

Ordered Yes Yes Yes No

Duplicate values Yes Yes Yes Keys must be unique

Item Assignment NOT allowed Allowed NOT allowed Allowed

Can grow/shrink No Yes No Yes

Keys immutable? N/A N/A N/A Yes

Sequence type Yes Yes Yes No


PYTHON ERRORS — CHAPTER 2

Strings
Error Cause
TypeError: str object does not support item assignment Trying to change a char: name[0] = "p"

IndexError Accessing index out of bounds: s[5] for "Hello"

TypeError Using + with string and number: "hello" + 5

TypeError Using * with two strings: "a" * "b"

TypeError: object of type int has no len() Applying len() on an integer

Lists
Error Cause
IndexError Accessing list element with out-of-bound index

ValueError index() called with item not in list

IndexError (runtime) pop() called on an empty list

ValueError remove() called with value not in list

ValueError: attempt to assign sequence of size X to slice of size Y Assigning sequence of different size to extended slice

Tuples
Error Cause
TypeError: tuple object does not support item assignment T[i] = element — tuples are immutable

TypeError: can only concatenate tuple (not "int") to tuple tpl + (3) — use tpl + (3,) instead

ValueError index() called with item not in tuple

Dictionaries
Error Cause
KeyError Accessing a key that does not exist: d["xyz"]

KeyError del d[key] where key does not exist

KeyError pop() on absent key without default value

TypeError Using mutable type (list/dict) as dictionary key


CUET MCQs — IMPORTANT
Q1. Which data type is mutable?
Ans: (a) String (b) Tuple (c) List ✓ (d) int
Q2. Output of [1,2,3] * 2?
Ans: (a) [2,4,6] (b) [1,2,3,1,2,3] ✓ (c) Error
Q3. Method that adds single element at end of list?
Ans: (a) insert() (b) extend() (c) append() ✓ (d) add()
Q4. T=(1,2,3); T[0]=10 will result in?
Ans: (a) T=(10,2,3) (b) TypeError ✓ (c) ValueError (d) IndexError
Q5. d={'a':1,'b':2}; print([Link]('c',0))?
Ans: (a) Error (b) None (c) 0 ✓ (d) 'c'
Q6. in operator on dictionary checks?
Ans: (a) Values (b) Keys ✓ (c) Both (d) Items
Q7. Which sorting compares adjacent elements?
Ans: (a) Insertion Sort (b) Bubble Sort ✓ (c) Both
Q8. For s="PYTHON", s[1:4] gives?
Ans: (a) 'YTH' ✓ (b) 'PYT' (c) 'THO' (d) 'YTHO'
Q9. L=[1,2]; [Link]([3,4]); len(L)?
Ans: (a) 4 (b) 3 ✓ (c) 2 (d) Error
Q10. Which CANNOT be a dictionary key?
Ans: (a) int (b) string (c) tuple (d) list ✓

ASSERTION-REASON QUESTIONS
Q1.
A: L=[1,2,3]; M=L; M[0]=99 will change L also.
R: Assignment = makes shallow copy — both point to same memory.
Answer: Both A and R are TRUE, R is correct explanation of A ✓
Q2.
A: Bubble Sort builds sorted list by inserting elements one by one.
R: In Bubble Sort, adjacent elements are compared and swapped.
Answer: A is FALSE, R is TRUE (A describes Insertion Sort, not Bubble Sort)
Q3.
A: (5) is a tuple in Python.
R: Tuples are created using parentheses.
Answer: A is FALSE, R is TRUE → (5) = int, (5,) = tuple
PREVIOUS YEAR BOARD QUESTIONS (CBSE)

2023 — 2 marks
Q: What is the difference between append() and extend() methods of list?
A: append() adds single item as one element; extend() adds all items of another list individually.

2022 — 3 marks
Q: Write a program to sort [34,12,45,2,89,23] using Bubble Sort.
A: Use nested for loop — outer for passes, inner for comparisons and swap adjacent if a[j]>a[j+1].

2021 — 2 marks
Q: Output of t=(1,2,3,4,5); print(t[1:3]); print(t[-2:])
A: (2, 3) and (4, 5)

2020 — 1 mark
Q: Name the method that returns all key-value pairs of dictionary as tuples.
A: items()

2019 — 2 marks
Q: Differentiate between shallow copy and deep copy of lists.
A: Shallow copy (b=a) — same memory, changes in one affect other. Deep copy (b=list(a)) — independent copy.

■ 10 MOST IMPORTANT POINTS TO REMEMBER


1. Strings are IMMUTABLE — s[0]='X' gives TypeError
2. Lists are MUTABLE — L[0]=X is valid
3. Tuples are IMMUTABLE — T[0]=X gives TypeError
4. Dictionaries are MUTABLE — values can be changed
5. Shallow copy (b=a) — same memory | Deep copy (b=list(a)) — different memory
6. append() adds ONE item | extend() adds MULTIPLE items
7. pop() RETURNS removed element | remove() returns None
8. Dictionary in operator checks KEYS only, not values
9. Bubble Sort = compare adjacent | Insertion Sort = insert at correct position
10. s[::-1] = reverse of string/list/tuple

All the Best for Your Exams! ■

You might also like