Python Revision Tour II Notes (1)
Python Revision Tour II Notes (1)
STRING
1. Introduction to Strings
Strings in Python are sequences of characters enclosed in single, double, or triple quotes. Strings are
immutable, meaning they cannot be changed after they are created.
# Example of a string
s = "Hello, World!"
2. Traversing a String
Traversing a string means iterating through each character of the string. You can do this using a for loop
or by using indexing.
s = "Hello"
for char in s:
print(char)
Output:
H
e
l
l
o
s = "Hello"
for i in range(len(s)):
print(s[i])
Output:
H
e
l
l
o
3. String Operators
4. String Slicing
String slicing allows you to extract a portion of a string. It uses the syntax: string[start:end:step].
Example Usage:
s = " Hello, World! "
# Strip spaces
Example:
2. Creation of List
Empty list
list1 = []
# Nested list
list4 = [1, [2, 3], 4]
3. List Operations
4. List Indexing
List Indexing:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (negative
indexing)
5. List Slicing
List Slicing:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[::2]) # [10, 30, 50]
6. Functions of List
A tuple is an ordered collection of items, which is immutable (i.e., it cannot be changed after
creation). Tuples are similar to lists but use round brackets () instead of square brackets [].
CHARACTERISTICS OF TUPLE
CREATION OF TUPLE:
1. Empty Tuple
t = ()
5. Nested Tuple
t = (1, 2, (3, 4), [5, 6])
Tuple Operations
Tuple Indexing:
Just like strings and lists, tuple elements can be accessed using indexes.
Tuple Slicing:
sum() Returns the sum of all elements sum(t) sum((10, 20, 30)) 60
Tuple Methods:
1. Introduction to Dictionary
🔹 Example:
student = {'name': 'John', 'age': 16, 'grade': 'A'}
🔹 Output:
{'name': 'John', 'age': 16, 'grade': 'A'}
🔹 Example:
car = {
'brand': 'Toyota',
'model': 'Corolla',
'year': 2022
}
Accessing a value:
print(car['model'])
🔹 Output:
Corolla
3. Working with Dictionaries
Removes
Delete a pair del d['grade'] Deletes key-value pair
'grade' key
Check key Returns True if key
'name' in d True
existence exists
Loop through 'name', 'age',
for k in d: Iterates over keys
keys etc.
🔹 Example Program:
student = {'name': 'John', 'age': 16, 'grade': 'A'}
# Access
print(student['name'])
# Modify
student['grade'] = 'A+'
# Add
student['city'] = 'Delhi'
# Delete
del student['age']
🔹 Output:
John
name : John
grade : A+
city : Delhi
4. Dictionary Functions & Methods
🔹 Example Program:
d = {'name': 'John', 'age': 25}
print(d['name']) # Accessing value
d['age'] = 30 # Modifying value
d['city'] = 'Delhi' # Adding new key:value
print(d.items()) # Getting all key-value pairs
Output:
John
dict_items([('name', 'John'), ('age', 30), ('city', 'Delhi')])