String
A string in Python is a sequence of characters enclosed in quotes.
It can include letters, numbers, symbols, and even spaces.
strings are immutable (cannot be changed after creation)
Indexing starts from 0
Strings can contain any character
Creating Strings Using Quotes
Single Quotes
s1 = 'Hello'
Double Quotes
s2 = "Hello"
Both are the same. Use whichever is convenient.
Triple Quotes (Multiline Strings)
Used when your string spans multiple lines.
s3 = '''This is
a multiline
string'''
or
s4 = """This is also
a multiline
string"""
Creating String with Special Characters
Using Escape Sequences
s = "Hello\nWorld"
print(s)
Output:
Hello
World
Common escape characters:
\n → New line
\t → Tab
\\ → Backslash
\' → Single quote
\" → Double quote
Raw Strings
If you don’t want escape sequences to be processed:
s = r"Hello\nWorld"
print(s)
Output:
Hello\nWorld
Useful for file paths:
path = r"C:\Users\Name\Documents"
Creating Strings Using str() Function
You can convert other data types into strings:
a = str(123)
b = str(45.67)
c = str(True)
print(a, b, c)
String Creation Using Concatenation
s = "Hello" + " " + "World"
print(s)
Output:
Hello World
String Creation Using Repetition
s = "Hi " * 3
print(s)
Output:
Hi Hi Hi
Creating Strings Using Formatting
Using f-strings (Best and modern way)
name = "Hemlata"
s = f"Hello {name}"
print(s)
Using format() method
s = "Hello {}".format("Hemlata")
Using % formatting (old style)
s = "Hello %s" % "Hemlata"
Empty String Creation
s = ""
Unicode Strings
Python supports Unicode by default:
s = "हेलो" # Hindi
Properties
Strings in Python have several important properties that define how they behave.
1. Ordered
Characters in a string are stored in a sequence.
Each character has a fixed position (index).
s = "hello"
print(s[0]) # h
2. Immutable
Strings cannot be changed after creation.
You cannot modify a single character directly.
s = "hello"
# s[0] = 'H' ❌ Error
# Instead, create a new string
s = "H" + s[1:]
print(s) # Hello
3. Allows Duplicates
Same characters can appear multiple times.
s = "programming"
print([Link]('m')) # 2
4. Heterogeneous Data (Not Allowed)
A string contains only characters (not different data types like lists).
But characters can be letters, digits, symbols.
s = "abc123!@"
5. Supports Indexing
Access characters using index.
Positive and negative indexing supported.
s = "python"
print(s[1]) # y
print(s[-1]) # n
6. Supports Slicing
Extract parts of a string.
s = "python"
print(s[1:4]) # yth
7. Iterable
You can loop through a string.
for ch in "abc":
print(ch)
8. Dynamic Size
Strings can grow or shrink (by creating new ones).
s = "hi"
s = s + " there"
print(s) # hi there
9. Supports Concatenation
Strings can be joined using +.
a = "hello"
b = "world"
print(a + " " + b) # hello world
10. Supports Repetition
Use * operator.
print("ha" * 3) # hahaha
11. Supports Membership Test
Check if a character or substring exists.
print("a" in "apple") # True
print("z" not in "apple") # True
12. Supports String Methods
Built-in functions like upper(), lower(), strip(), etc.
s = "hello"
print([Link]()) # HELLO
Indexing
String Indexing in Python is how you access individual characters from a string using
their position (index).
Each character in a string has a position number.
Types of Indexing
1. Positive Indexing
Starts from 0
Moves from left to right
s = "Python"
print(s[0]) # P
print(s[3]) # h
2. Negative Indexing
Starts from -1
Moves from right to left
s = "Python"
print(s[-1]) # n
print(s[-3]) # h
Slicing
Slicing means extracting a part (substring) of a string using a specific range of indices.
Syntax
string[start : end : step]
start → index where slicing begins (included)
end → index where slicing stops (excluded)
step → how many steps to jump (optional)
Example
s = "Python"
Index positions:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Common Slicing Examples
1. Basic slicing
print(s[0:4]) # Pyth
2. Omitting start
print(s[:4]) # Pyth (starts from 0)
3. Omitting end
print(s[2:]) # thon (goes till end)
4. Full string
print(s[:]) # Python
Using Step
5. Skip characters
print(s[0:6:2]) # Pto
6. Reverse string
print(s[::-1]) # nohtyP
Negative Indexing
7. From the end
print(s[-4:-1]) # tho
Methods
1. find()
Returns the index of the first occurrence (or -1 if not found)
text = "hello world"
print([Link]("world")) # 6
print([Link]("python")) # -1
2. index()
Same as find(), but raises an error if not found
text = "hello world"
print([Link]("world")) # 6
# print([Link]("python")) → ValueError
3. upper()
Converts to uppercase
text = "hello"
print([Link]()) # HELLO
4. lower()
Converts to lowercase
text = "HELLO"
print([Link]()) # hello
5. title()
Capitalizes first letter of each word
text = "hello world"
print([Link]()) # Hello World
6. capitalize()
Capitalizes only the first letter of the string
text = "hello world"
print([Link]()) # Hello world
7. swapcase()
Swaps uppercase to lowercase and vice versa
text = "Hello World"
print([Link]()) # hELLO wORLD
8. casefold()
More aggressive lowercase (used for comparisons)
text = "HELLO"
print([Link]()) # hello
9. isalpha()
Checks if all characters are alphabets
text = "hello"
print([Link]()) # True
text = "hello123"
print([Link]()) # False
10. isdigit()
Checks if all characters are digits
text = "12345"
print([Link]()) # True
11. isalnum()
Checks if alphanumeric (letters + numbers)
text = "abc123"
print([Link]()) # True
12. isspace()
Checks if string contains only whitespace
text = " "
print([Link]()) # True
13. replace()
Replaces substring
text = "hello world"
print([Link]("world", "python")) # hello python
14. strip()
Removes spaces from both ends
text = " hello "
print([Link]()) # "hello"
15. split()
Splits string into list
text = "hello world python"
print([Link]()) # ['hello', 'world', 'python']
16. join()
Joins list into string
words = ['hello', 'world']
print(" ".join(words)) # hello world
String formatting
String formatting in Python is the way you insert values (variables, expressions) into
strings in a clean and readable way. Python provides multiple methods for this:
Using f-strings (Recommended)
Introduced in Python 3.6 — easiest and most modern way.
name = "Hemlata"
age = 20
print(f"My name is {name} and I am {age} years old")
You can also use expressions:
print(f"Next year I will be {age + 1}")
Using format() method
Works in older versions too.
name = "Hemlata"
age = 20
print("My name is {} and I am {} years old".format(name, age))
With positions:
print("My name is {0} and I am {1}".format(name, age))
With keywords:
print("My name is {n} and I am {a}".format(n=name, a=age))
Using % formatting (Old style)
Similar to C language formatting.
name = "Hemlata"
age = 20
print("My name is %s and I am %d years old" % (name, age))
Formatting numbers
pi = 3.14159
print(f"Value of pi: {pi:.2f}") # 2 decimal places
Alignment and spacing
text = "Python"
print(f"{text:<10}") # Left aligned
print(f"{text:>10}") # Right aligned
print(f"{text:^10}") # Center aligned
Padding with zeros
num = 5
print(f"{num:03}") # Output: 005
List
A list is a collection of items stored in a single variable.
Ordered (keeps insertion order)
Mutable (can be changed)
Allows duplicate values
Can store different data types
Syntax:-
list_name = [element1, element2, element3, ...]
Ways to Create a List in Python
Empty List
You can create an empty list in two ways:
list1 = []
list2 = list()
List with Elements
numbers = [10, 20, 30, 40]
List with Different Data Types
Python lists can hold mixed data:
mixed = [10, "hello", 3.14, True]
Using list() Constructor
Convert other data types into a list:
l1 = list("hello") # ['h', 'e', 'l', 'l', 'o']
l2 = list((1, 2, 3)) # tuple → list
l3 = list({1, 2, 3}) # set → list
Using range() Function
Useful for generating number lists:
numbers = list(range(5)) # [0, 1, 2, 3, 4]
numbers2 = list(range(1, 6)) # [1, 2, 3, 4, 5]
numbers3 = list(range(1, 10, 2)) # [1, 3, 5, 7, 9]
Properties
1. Ordered
Lists maintain the order of elements as you insert them.
lst = [10, 20, 30]
print(lst) # [10, 20, 30]
2. Mutable (Changeable)
You can modify a list after creating it.
lst = [1, 2, 3]
lst[1] = 99
print(lst) # [1, 99, 3]
👉 You can add, remove, or update elements anytime.
3. Allows Duplicates
Lists can store the same value multiple times.
lst = [1, 2, 2, 3, 3, 3]
print(lst) # [1, 2, 2, 3, 3, 3]
4. Allows Heterogeneous Data
A list can hold different data types together.
lst = [10, "hello", 3.14, True]
print(lst)
5. Dynamic Size
Lists grow or shrink automatically.
lst = [1, 2]
[Link](3)
[Link](4)
print(lst) # [1, 2, 3, 4]
6. Supports Indexing
You can access elements using position (index starts at 0).
lst = [10, 20, 30]
print(lst[0]) # 10
print(lst[-1]) # 30 (last element)
7. Supports Slicing
You can extract a portion of the list.
lst = [10, 20, 30, 40, 50]
print(lst[1:4]) # [20, 30, 40]
Format: list[start:end:step]
8. Iterable
Lists can be looped through easily.
lst = [1, 2, 3]
for i in lst:
print(i)
9. Packing
Putting multiple values into a single list.
lst = 1, 2, 3
print(lst) # (1, 2, 3) → actually tuple packing
lst = [1, 2, 3] # list packing
👉 Packing means grouping values together.
10. Unpacking
Extracting values from a list into variables.
lst = [10, 20, 30]
a, b, c = lst
print(a) # 10
print(b) # 20
print(c) # 30
Summary
Ordered → Keeps sequence
Mutable → Can be changed
Duplicates → Allowed
Heterogeneous → Mixed data types
Dynamic → Size can change
Indexing → Access by position
Slicing → Extract parts
Iterable → Loop through
Packing → Group values
Unpacking → Assign values to variables
Indexing
Indexing means accessing individual elements of a list using their position.
In Python, lists are ordered, so every element has an index (position number).
Example
my_list = [10, 20, 30, 40, 50]
Element Index
10 0
20 1
30 2
40 3
50 4
Positive Indexing
Starts from 0 (left to right)
print(my_list[0]) # 10
print(my_list[2]) # 30
print(my_list[4]) # 50
Negative Indexing
Starts from -1 (right to left)
Element Index
10 -5
20 -4
30 -3
40 -2
50 -1
print(my_list[-1]) # 50
print(my_list[-3]) # 30
Accessing Elements
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # banana
print(fruits[-1]) # cherry
Modifying Elements Using Index
Lists are mutable, so you can change values:
my_list = [1, 2, 3]
my_list[1] = 100
print(my_list) # [1, 100, 3]
Index Out of Range Error
If you use an invalid index, Python gives an error:
my_list = [1, 2, 3]
print(my_list[5]) # Error!
❌ Output:
IndexError: list index out of range
Nested List Indexing
Lists can contain other lists:
nested = [[1, 2], [3, 4], [5, 6]]
print(nested[0]) # [1, 2]
print(nested[0][1]) # 2
Methods
1. append()
Adds a single element to the end of the list.
numbers = [1, 2, 3]
[Link](4)
print(numbers) # [1, 2, 3, 4]
2. extend()
Adds multiple elements (from another list/iterable).
numbers = [1, 2, 3]
[Link]([4, 5])
print(numbers) # [1, 2, 3, 4, 5]
3. insert()
Inserts an element at a specific index.
numbers = [1, 2, 3]
[Link](1, 10)
print(numbers) # [1, 10, 2, 3]
4. remove()
Removes the first occurrence of a value.
numbers = [1, 2, 3, 2]
[Link](2)
print(numbers) # [1, 3, 2]
5. pop()
Removes and returns element by index (default = last).
numbers = [1, 2, 3]
x = [Link]()
print(x) #3
print(numbers) # [1, 2]
6. clear()
Removes all elements from the list.
numbers = [1, 2, 3]
[Link]()
print(numbers) # []
7. index()
Returns the index of the first occurrence.
numbers = [1, 2, 3, 2]
print([Link](2)) # 1
8. count()
Counts how many times an element appears.
numbers = [1, 2, 2, 3]
print([Link](2)) # 2
9. sort()
Sorts the list in ascending order (in-place).
numbers = [3, 1, 2]
[Link]()
print(numbers) # [1, 2, 3]
Descending:
[Link](reverse=True)
print(numbers) # [3, 2, 1]
10. copy()
Returns a shallow copy of the list.
numbers = [1, 2, 3]
new_list = [Link]()
print(new_list) # [1, 2, 3]
11. reverse()
Reverses the list in-place.
numbers = [1, 2, 3]
[Link]()
print(numbers) # [3, 2, 1]
List comprehension
List comprehension in Python is a compact and elegant way to create lists in a single
line, instead of using multiple lines with loops.
Syntax
[expression for item in iterable]
Example 1: Simple list
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
Instead of writing a loop:
squares = []
for x in numbers:
[Link](x**2)
Example 2: With condition (if)
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
Output:
[2, 4, 6]
Example 3: If-Else in list comprehension
numbers = [1, 2, 3, 4]
result = ["Even" if x % 2 == 0 else "Odd" for x in numbers]
print(result)
Output:
['Odd', 'Even', 'Odd', 'Even']
Example 4: Nested loops
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs)
Output:
[(1, 3), (1, 4), (2, 3), (2, 4)]
Example 5: Working with strings
word = "python"
letters = [[Link]() for char in word]
print(letters)
Output:
['P', 'Y', 'T', 'H', 'O', 'N']
Tuple
A tuple in Python is a built-in data type used to store a collection of items. It is similar to a
list, but immutable (cannot be changed after creation).
Ways to Create a Tuple in Python
Using parentheses ()
t1 = (1, 2, 3, 4)
print(t1)
Without parentheses (tuple packing)
t2 = 10, 20, 30
print(t2)
Single element tuple (important!)
You must include a comma, otherwise it is not a tuple.
t3 = (5,) # सही tuple
t4 = (5) # not a tuple, it's an integer
print(type(t3)) # <class 'tuple'>
print(type(t4)) # <class 'int'>
Using tuple() constructor
t5 = tuple([1, 2, 3]) # from list
t6 = tuple("hello") # from string
print(t5) # (1, 2, 3)
print(t6) # ('h', 'e', 'l', 'l', 'o')
Empty tuple
t7 = ()
print(t7)
Nested Tuple
t8 = (1, (2, 3), 4)
print(t8)
Tuple Packing and Unpacking
Packing:
t = 1, 2, 3
Unpacking:
a, b, c = t
print(a, b, c)
Tuple Properties in Python
1. Ordered
Tuples maintain the order of elements as they are inserted.
t = (10, 20, 30)
print(t[0]) # Output: 10
👉 The order will not change unless you create a new tuple.
2. Immutable (Read-only)
Once a tuple is created, you cannot modify, add, or remove elements.
t = (1, 2, 3)
t[0] = 10 # ❌ Error: 'tuple' object does not support item assignment
3. Allows Duplicates
Tuples can contain duplicate values.
t = (1, 2, 2, 3)
print(t) # Output: (1, 2, 2, 3)
4. Heterogeneous (Mixed Data Types)
A tuple can store elements of different data types.
t = (1, "Python", 3.5, True)
print(t)
5. Supports Indexing
You can access elements using index numbers.
t = (10, 20, 30)
print(t[1]) # Output: 20
print(t[-1]) # Output: 30 (negative indexing)
6. Supports Slicing
You can extract a portion of a tuple.
t = (1, 2, 3, 4, 5)
print(t[1:4]) # Output: (2, 3, 4)
7. Iterable
You can loop through tuple elements.
t = (1, 2, 3)
for i in t:
print(i)
8. Supports Packing and Unpacking
Packing:
t = 1, 2, 3 # Automatically creates a tuple
Unpacking:
a, b, c = t
print(a, b, c) # Output: 1 2 3
9. Can be Nested
Tuples can contain other tuples.
t = ((1, 2), (3, 4))
print(t[0]) # Output: (1, 2)
10. Faster than Lists
Tuples are generally faster than lists because they are immutable.
11. Hashable (If elements are immutable)
Tuples can be used as keys in dictionaries if all elements are immutable.
t = (1, 2, 3)
d = {t: "value"}
print(d)
Indexing
Tuple indexing in Python is how you access individual elements inside a tuple using their
position.
Index always starts from 0
Negative index starts from -1
Tuples are immutable, so you cannot change values using indexing
Positive Indexing
Starts from the beginning (left → right)
t = (10, 20, 30, 40, 50)
print(t[0]) # Output: 10
print(t[2]) # Output: 30
print(t[4]) # Output: 50
Negative Indexing
Starts from the end (right → left)
t = (10, 20, 30, 40, 50)
print(t[-1]) # Output: 50
print(t[-2]) # Output: 40
print(t[-5]) # Output: 10
Accessing Nested Tuple Elements
t = (1, (2, 3), 4)
print(t[1]) # Output: (2, 3)
print(t[1][0]) # Output: 2
Index Out of Range
If you use an invalid index, Python gives an error:
print(t[10]) # IndexError
Methods
Tuples in Python are immutable, which means you cannot change their elements after
creation. Because of this, tuples have very few built-in methods compared to lists.
Python provides only two main methods for tuples:
1. count()
Returns the number of times a specified value appears in the tuple.
Syntax:
tuple_name.count(value)
Example:
t = (1, 2, 3, 2, 4, 2)
print([Link](2))
Output:
Here, 2 appears 3 times in the tuple.
2. index()
Returns the index of the first occurrence of a specified value.
Syntax:
tuple_name.index(value)
Example:
t = (10, 20, 30, 20, 40)
print([Link](20))
Output:
It returns the index of the first 20, not all occurrences.
Set
A set in Python is a collection data type used to store multiple unique elements.
It is defined using curly braces {} or the set() function.
Sets are mainly used when you want to avoid duplicate values and perform
mathematical operations like union, intersection, etc.
Example:
my_set = {1, 2, 3, 4}
print(my_set)
# Using set() function
another_set = set([1, 2, 2, 3])
print(another_set) # Output: {1, 2, 3}
Properties of Set in Python
1. Unordered
Elements do not follow a fixed order
s = {3, 1, 2}
print(s) # Output may be {1, 2, 3}
2. No Duplicate Elements
Automatically removes duplicates
s = {1, 2, 2, 3}
print(s) # Output: {1, 2, 3}
3. Mutable
You can add or remove elements
s = {1, 2}
[Link](3)
[Link](1)
print(s)
4. No Indexing or Slicing
You cannot access elements using index
s = {1, 2, 3}
# print(s[0]) ❌ Error
5. Heterogeneous Allowed
Can store different data types
s = {1, "hello", 3.5}
6. Dynamic Size
Size can grow or shrink
s = {1, 2}
[Link](3)
7. Iterable
You can loop through elements
for i in {1, 2, 3}:
print(i)
8. Only Immutable Elements Allowed
Elements must be immutable (cannot change)
s = {1, 2, (3, 4)} # ✅ valid
# s = {1, [2, 3]} ❌ invalid (list is mutable)
Set operations
Set operations in Python are used to perform mathematical operations like union, intersection,
difference, etc., on sets. Since sets store unique and unordered elements, these operations are fast and
very useful in real-world problems like filtering data.
[Link] ( | or .union() )
Combines elements from both sets (no duplicates).
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # {1, 2, 3, 4, 5}
print([Link](B)) # {1, 2, 3, 4, 5}
2. Intersection ( & or .intersection() )
Returns common elements in both sets.
A = {1, 2, 3}
B = {2, 3, 4}
print(A & B) # {2, 3}
print([Link](B)) # {2, 3}
3. Difference ( - or .difference() )
Returns elements present in one set but not in the other.
A = {1, 2, 3}
B = {2, 4, 5}
print(A - B) # {1, 3}
print([Link](B)) # {1, 3}
4. Symmetric Difference ( ^ or .symmetric_difference() )
Returns elements that are in either set, but not in both.
A = {1, 2, 3}
B = {2, 3, 4}
print(A ^ B) # {1, 4}
print(A.symmetric_difference(B)) # {1, 4}
Methods
1. Adding Elements
add()
Adds a single element to the set.
s = {1, 2, 3}
[Link](4)
print(s) # {1, 2, 3, 4}
update()
Adds multiple elements (from list, tuple, set, etc.).
s = {1, 2}
[Link]([3, 4], {5, 6})
print(s) # {1, 2, 3, 4, 5, 6}
2. Removing Elements
remove()
Removes an element. Raises error if not found.
s = {1, 2, 3}
[Link](2)
print(s) # {1, 3}
discard()
Removes an element. No error if not found.
[Link](5) # No error
pop()
Removes and returns a random element.
s = {10, 20, 30}
print([Link]()) # Random element
clear()
Removes all elements.
[Link]()
print(s) # set()
3. Set Operations
union()
Combines two sets (no duplicates).
a = {1, 2}
b = {2, 3}
print([Link](b)) # {1, 2, 3}
intersection()
Common elements.
print([Link](b)) # {2}
difference()
Elements in first set but not in second.
print([Link](b)) # {1}
symmetric_difference()
Elements in either set but not both.
print(a.symmetric_difference(b)) # {1, 3}
4. Set Relationship Methods
issubset()
Checks if all elements of one set are in another.
a = {1, 2}
b = {1, 2, 3}
print([Link](b)) # True
issuperset()
Checks if a set contains another set.
print([Link](a)) # True
isdisjoint()
Checks if sets have no common elements.
print([Link]({4, 5})) # True
5. Copying Sets
copy()
Creates a shallow copy.
s = {1, 2, 3}
new_s = [Link]()
Dictionary
A dictionary in Python is a built-in data type used to store data in key–value pairs. Think
of it like a real-world dictionary where you look up a word (key) to find its meaning (value).
Syntax
dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
Example
student = {
"name": "Hemlata",
"age": 20,
"course": "[Link]"
}
print(student)
Output:
{'name': 'Hemlata', 'age': 20, 'course': '[Link]'}
Properties of Dictionary in Python
1. Unordered (logically) but maintains insertion order
Earlier (before Python 3.7), dictionaries were unordered.
Now, they preserve the order in which elements are added.
d = {"a": 1, "b": 2, "c": 3}
print(d) # Output: {'a': 1, 'b': 2, 'c': 3}
2. Mutable (changeable)
You can add, update, or delete items after creation.
d = {"name": "John"}
d["age"] = 25 # Add
d["name"] = "Mike" # Update
del d["age"] # Delete
3. Keys must be unique
Duplicate keys are not allowed.
If you repeat a key, the latest value overwrites the previous one.
d = {"a": 1, "a": 2}
print(d) # Output: {'a': 2}
4. Keys must be immutable
Keys can be: int, float, string, tuple
Keys cannot be: list, set, dict
d = {1: "one", "name": "John", (1, 2): "tuple"} # Valid
# d = {[1,2]: "list"} # ❌ Invalid
5. Values can be any data type
Values can be anything: numbers, strings, lists, tuples, even other dictionaries.
d={
"name": "John",
"marks": [90, 85],
"details": {"age": 20}
}
6. Indexed by keys (not positions)
Access elements using keys, not index numbers.
d = {"name": "John", "age": 25}
print(d["name"]) # Output: John
7. Dynamic size
Dictionary size can grow or shrink as needed.
d = {}
d["a"] = 10
d["b"] = 20
8. Iterable
You can loop through dictionaries.
d = {"a": 1, "b": 2}
for key in d:
print(key, d[key])
9. Supports nesting
A dictionary can contain another dictionary.
d={
"student": {
"name": "John",
"age": 20
}
}
Accessing elements from a dictionary
Accessing elements from a dictionary in Python is straightforward once you know the
basics. A dictionary stores data as key–value pairs, and you use the key to get the value.
1. Access using square brackets []
This is the most common method.
student = {"name": "Ram", "age": 20, "course": "Python"}
print(student["name"]) # Output: Ram
print(student["age"]) # Output: 20
If the key doesn’t exist, this will raise an error (KeyError).
2. Access using .get() method
Safer way to access values.
print([Link]("name")) # Output: Ram
print([Link]("marks")) # Output: None
You can also give a default value:
print([Link]("marks", "Not Available"))
# Output: Not Available
3. Access all keys
print([Link]())
# Output: dict_keys(['name', 'age', 'course'])
4. Access all values
print([Link]())
# Output: dict_values(['Ram', 20, 'Python'])
5. Access key–value pairs
print([Link]())
# Output: dict_items([('name', 'Ram'), ('age', 20), ('course', 'Python')])
6. Using loop to access elements
for key in student:
print(key, ":", student[key])
Or:
for key, value in [Link]():
print(key, ":", value)
7. Access nested dictionary
data = {
"student": {
"name": "Ram",
"age": 20
}
}
print(data["student"]["name"]) # Output: Ram
Methods
Dictionary methods are built-in functions provided by Python to perform operations
on dictionaries, such as adding, removing, updating, and accessing data.
Methods in dictionary are listed below:-
1. get()
Safely access a value using a key (no error if key is missing)
student = {"name": "Ram", "age": 20}
print([Link]("name")) # Ram
print([Link]("marks")) # None
print([Link]("marks", 0)) # 0 (default value)
2. keys()
Returns all keys
print([Link]())
# dict_keys(['name', 'age'])
3. values()
Returns all values
print([Link]())
# dict_values(['Ram', 20])
4. items()
Returns key-value pairs as tuples
print([Link]())
# dict_items([('name', 'Ram'), ('age', 20)])
5. update()
Adds or updates multiple key-value pairs
[Link]({"age": 21, "marks": 85})
print(student)
# {'name': 'Ram', 'age': 21, 'marks': 85}
6. pop()
Removes a specific key
[Link]("age")
print(student)
# {'name': 'Ram', 'marks': 85}
7. popitem()
Removes the last inserted key-value pair
[Link]()
print(student)
8. clear()
Removes all elements
[Link]()
print(student) # {}
9. copy()
Creates a shallow copy
new_student = [Link]()
10. setdefault()
Returns value if key exists, otherwise adds key with default value
student = {"name": "Ram"}
[Link]("age", 20)
print(student)
# {'name': 'Ram', 'age': 20}
11. fromkeys()
Creates a dictionary with given keys and same value
keys = ["a", "b", "c"]
new_dict = [Link](keys, 0)
print(new_dict)
# {'a': 0, 'b': 0, 'c': 0}
Dictionary comprehension
Dictionary comprehension in Python is a concise way to create dictionaries using a single
line of code, similar to list comprehension.
Syntax
{key: value for item in iterable}
Example
# Create a dictionary with numbers and their squares
squares = {x: x**2 for x in range(5)}
print(squares)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
With Condition
You can also add conditions using if.
# Only even numbers
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
Output:
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Using Existing Dictionary
# Convert values to uppercase
data = {'a': 'apple', 'b': 'banana', 'c': 'cherry'}
upper_data = {k: [Link]() for k, v in [Link]()}
print(upper_data)
Output:
{'a': 'APPLE', 'b': 'BANANA', 'c': 'CHERRY'}
Swap Keys and Values
data = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in [Link]()}
print(swapped)
Output:
{1: 'a', 2: 'b', 3: 'c'}
Iterating over a dictionary
Iterating over a dictionary in Python means going through its keys, values, or key-value
pairs one by one. Since dictionaries are a core data structure, Python gives you multiple
clean ways to iterate depending on what you need.
1. Iterating over Keys (default way)
By default, a dictionary loop gives you keys.
student = {"name": "Ravi", "age": 21, "course": "CS"}
for key in student:
print(key)
Output:
name
age
course
2. Iterating over Values
Use .values() when you only care about values.
for value in [Link]():
print(value)
Output:
Ravi
21
CS
3. Iterating over Key-Value Pairs
Use .items() when you need both key and value.
for key, value in [Link]():
print(key, ":", value)
👉 Output:
name : Ravi
age : 21
course : CS
4. Iterating with Index (using enumerate)
If you want an index along with items:
for i, (key, value) in enumerate([Link]()):
print(i, key, value)
Output:
0 name Ravi
1 age 21
2 course CS
5. Iterating in Sorted Order
To loop in sorted key order:
for key in sorted(student):
print(key, student[key])
6. Iterating with Condition
You can filter while iterating:
for key, value in [Link]():
if value == 21:
print(key)
Output:
age
7. Nested Dictionary Iteration
For dictionaries inside dictionaries:
students = {
"s1": {"name": "Ravi", "age": 21},
"s2": {"name": "Anu", "age": 22}
}
for key, value in [Link]():
print(key)
for inner_key, inner_value in [Link]():
print(inner_key, ":", inner_value)