Unit-2 Python (Full QB Solved) Final
Unit-2 Python (Full QB Solved) Final
2m
A string is a sequence of characters in Python. Strings can be created using single quotes, double quotes, or triple quotes. Two
common methods are using single quotes and double quotes.
Example:
2. List any two built-in functions used with python strings with their use.
Python provides many built-in functions for strings. The len() function is used to find the number of characters in a string. The
max() function returns the character with the highest ASCII/Unicode value.
Example:
text = "Python"
print(len(text)) # 6
print(max(text)) # y
Strings are called immutable because once a string is created, its characters cannot be changed. Python does not allow direct
modification of string elements. Instead, a new string must be created.
Example:
immu = "dollar"
# immu[0] = 'c' → Error
Output:
collar
Negative indexing is used to access characters from the end of a string or list. The index -1 represents the last character, -2
represents the second last character, and so on. It is useful when accessing elements from the end.
Example:
print(word_phrase[-1])
print(word_phrase[-2])
Output:
f
l
Membership operators in and not in are used to check whether a substring exists in a string. They return True if the value is
found and False otherwise. These operators are commonly used in conditions.
Example:
greeting = "Hello world"
print('world' in greeting)
print('Python' not in greeting)
Output:
True
True
S = 'Python is easy'
print( "Slice of String : ", S[ : : 2] )
print ("Slice of String : ", S[-1: 5 :-1 ] )
Output:
The split() function is used to break a string into smaller parts and returns them as a list. The string is split based on a
separator. If no separator is given, whitespace is used by default.
Syntax:
string_name.split([separator [, maxsplit]])
Example:
Output:
The join() method is used to combine multiple strings into a single string. A separator string is inserted between each element
of the sequence. All items in the sequence must be strings.
Syntax:
string_name.join(sequence)
Example:
Output:
This is a list
A palindrome is a string that reads the same forward and backward. In Python, it can be checked by comparing the original
string with its reverse. String slicing is used to reverse the string.
Program:
if text == text[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
A list is a collection of elements that are ordered and mutable. Lists can contain different data types such as numbers, strings,
and even other lists. Lists are created using square brackets [ ].
Example:
Output:
Python provides several built-in functions for lists. The len() function finds the number of elements, sum() calculates the total
of numeric values, sorted() sorts the list, and any() checks if at least one element is True.
Example:
numbers = [1, 2, 3, 4]
print(len(numbers))
print(sum(numbers))
print(sorted(numbers))
print(any([True, False]))
Basic operations on lists include concatenation, repetition, indexing, slicing, and membership testing. Concatenation joins two
lists using +, while repetition repeats elements using *. Lists also support indexing and slicing to access elements.
Example:
list1 = [1, 2]
list2 = [3, 4]
print(list1 + list2)
print(list1 * 2)
Output:
[1, 2, 3, 4]
[1, 2, 1, 2]
The append() method adds an element at the end of the list. The insert() method inserts an element at a specified position in
the list. These methods are commonly used for modifying lists.
Example:
numbers = [1, 2, 3]
[Link](4)
[Link](1, 10)
print(numbers)
Output:
[1, 10, 2, 3, 4]
14. What is Nested List? Give example.
A nested list is a list that contains one or more lists as its elements. It is used to store data in a matrix-like structure. Nested
lists can be accessed using multiple indexes.
Example:
print(nested_list)
print(nested_list[1][2])
Output:
Output:
A dictionary is a collection of key:value pairs. Each key in a dictionary is unique and is used to access its corresponding value.
Dictionaries are created using curly braces { }.
Example:
print(student)
Output:
17. Write any two built-in functions in dictionary with their use.
The dict() function is used to create a dictionary. The len() function is used to find the number of key:value pairs in a
dictionary. These functions help in creating and managing dictionaries.
Example:
print(numbers)
print(len(numbers))
Output:
A tuple is an ordered collection of elements in Python. Tuples are immutable, which means their elements cannot be changed
after creation. Tuples are created using parentheses ( ).
Example:
colors = ("red", "green", "blue")
print(colors)
Output:
Lists are mutable, which means their elements can be modified after creation. Tuples are immutable and cannot be changed
once created. Lists use square brackets [ ] while tuples use parentheses ( ).
Example:
list1 = [1, 2, 3]
tuple1 = (1, 2, 3)
20. Write any two built-in function in tuple with their use.
The len() function is used to find the number of elements in a tuple. The max() function returns the largest element in the
tuple. These functions are commonly used with tuples.
Example:
print(len(numbers))
print(max(numbers))
Output:
4
40
A tuple can be converted into a list using the list() function. This is useful when we want to modify tuple elements because
lists are mutable.
Example:
tuple_data = (1, 2, 3)
list_data = list(tuple_data)
print(list_data)
Output:
[1, 2, 3]
Tuple packing means storing multiple values into a single tuple. Tuple unpacking means extracting tuple elements into
separate variables. Python allows both operations easily.
Example:
# Packing
student = ("Ravi", 20, "BCA")
# Unpacking
name, age, course = student
print(name)
print(age)
print(course)
Output:
Ravi
20
BCA
A set is an unordered collection of unique elements. Sets do not allow duplicate values and are useful for mathematical set
operations. Sets are created using curly braces { }.
Example:
numbers = {1, 2, 3, 4}
print(numbers)
24. List two set methods and mention the purpose of each method.
The add() method is used to add an element to a set. The remove() method is used to remove a specific element from a set.
These methods help in modifying set elements.
Example:
[Link]("blue")
[Link]("green")
print(colors)
Output:
{'red', 'blue'}
A tuple is an ordered and immutable collection, while a set is unordered and mutable. Tuples allow duplicate values, but sets
store only unique elements. Tuples use ( ) whereas sets use { }.
Example:
tuple_data = (1, 2, 2, 3)
set_data = {1, 2, 2, 3}
print(tuple_data)
print(set_data)
Output:
(1, 2, 2, 3)
{1, 2, 3}
5 marks
[Link] is String? Explain how strings are created in Python with example.
A string is one of the most commonly used data types in Python. It is used to store and manipulate textual data such as
names, sentences, and messages.
Characteristics of Strings
• Strings are ordered (characters have index positions)
Example
s1 = 'Hello'
print(s1)
Output: Hello
Example
s2 = "Python Programming"
print(s2)
Example
s3 = '''Hello
Welcome to Python'''
print(s3)
Output:
Hello
Welcome to Python
Example
num = 123
s4 = str(num)
print(s4)
print(type(s4))
Output:
123
<class 'str'>
Strings can include special characters using escape sequences like \n, \t, etc.
Example
s5 = "Hello\nWorld"
print(s5)
Output:
Hello
World
Example
Important Points
Strings are fundamental in Python for handling text data. They can be created using single quotes, double quotes, triple
quotes, and functions like str(). Understanding string creation methods is essential for effective programming and text
manipulation.
A string is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' '''). Python
provides several operations that can be performed on strings. These operations help in combining, comparing, accessing, and
manipulating string data. The basic operations performed on strings are:
1. Concatenation
2. Repetition
3. Membership Operators
4. String Comparison
5. Indexing
6. Slicing
7. Traversing Strings
1. Concatenation (+)
Syntax
string1 + string2
Example
s1 = "Hello"
s2 = "World"
Output
Hello World
Output
50cent
Explanation
Here, the number 50 is converted into a string using str() and then joined with "cent".
2. Repetition (*)
Syntax
string * number
Example
print("Hi! " * 3)
Output
Explanation
Membership operators are used to check whether a character or substring exists inside a string.
Python provides two membership operators:
• in
• not in
(a) in Operator
Syntax
value in string
Example
print("World" in greeting)
print("Python" in greeting)
Output
True
False
Example
Output
True
Explanation
4. String Comparison
• ==
• !=
• <
• >
• <=
• >=
Example
print("january" == "jane")
print("january" > "jane")
print("A" < "a")
Output
False
True
True
Explanation
Capital letters have smaller ASCII values than lowercase letters. Hence "A" < "a" is True.
5. Indexing
• -1 → last character
Syntax
string[index]
Example
text = "Python"
print(text[0])
print(text[1])
print(text[-1])
Output
P
y
n
Explanation
text[0] gives the first character and text[-1] gives the last character.
6. String Slicing
Syntax
string[start:stop]
Example 1
print(text[0:6])
Output
Python
Example 2
print(text[7:])
Output
Programming
Syntax
string[start:stop:step]
Example
print(text[0:18:2])
Output
Pto rgamn
Explanation
7. Traversing a String
Traversing means accessing each character of a string one by one.
It can be done using loops such as for loop or while loop.
Syntax
Example
text = "Python"
Output
Python
Explanation
The loop takes one character at a time from the string and prints it.
A string is a sequence of characters stored in a specific order. In Python, characters in a string can be accessed using indexing
and slicing. These concepts are very important because they help us retrieve individual characters or parts of a string easily.
1. Indexing in Strings
Indexing means accessing individual characters of a string using their position number.
Python follows 0-based indexing, which means:
Python also supports negative indexing, where counting starts from the end of the string.
• Last character → -1
Syntax of Indexing
string_name[index]
Where:
text = "Python"
print(text[0])
print(text[1])
print(text[2])
Output
P
y
t
Explanation
Negative Indexing
Negative indexing is used to access characters from the end of the string.
It is useful when we want to access the last characters without knowing the exact length of the string.
print(word_phrase[-1])
print(word_phrase[-2])
print(word_phrase[-3])
Output
f
l
e
Explanation
Thus, indexing allows us to access characters from both beginning and end.
2. Slicing in Strings
Slicing is very useful when we need only a portion of a string instead of the whole string.
string_name[start:stop]
Where:
Python includes the start index but excludes the stop index.
substring1 = text[0:6]
print(substring1)
Output
Python
Explanation
substring2 = text[7:]
print(substring2)
Output
Programming
Explanation
• Start index is 7
substring3 = text[:6]
print(substring3)
Output
Python
Explanation
Syntax
string_name[start:stop:step]
Where:
Example
substring = text[0:18:2]
print(substring)
Output
Pto rgamn
Explanation
Example 1
print(text[-11:-1])
Output
Programmin
Explanation
Example 2
print(text[-5:])
Output
mming
Explanation
A string can also be reversed using slicing with negative step value.
Example
text = "Python"
print(text[::-1])
Output
nohtyP
Explanation
String methods in Python are built-in functions that help in performing different operations on strings. Among them, join()
and split() are very important methods used for combining and separating strings. These methods are widely used in text
processing and data handling.
1. split() Method
Syntax of split()
string_name.split([separator [, maxsplit]])
Explanation
print([Link](","))
Output
Explanation
print([Link]())
Output
Explanation
No separator is given, so Python automatically uses whitespace (space) to split the string.
Output
Explanation
• maxsplit = 2
2. join() Method
The join() method is used to combine multiple strings into one string.
It inserts a specified separator between the elements of a sequence.
• List
• Tuple
• String
Syntax of join()
string_name.join(sequence)
Explanation
print(joined_string)
Output
This is a list
Explanation: A space " " is inserted between each word in the list.
new_string = ":".join(words)
print(new_string)
Output
This:is:a:list
numbers = "123"
characters = "amy"
password = [Link](characters)
print(password)
Output
a123m123y
Explanation: The string "123" is inserted between each character of "amy".
Python provides many built-in string methods that are used to perform different operations on strings. String methods help in
modifying, searching, formatting, and processing text easily. These methods are very useful in Python programming and text
manipulation.
1. upper()
2. lower()
3. replace()
4. split()
5. join()
Additional methods:
6. strip()
7. find()
1. upper() Method
The upper() method converts all lowercase letters of a string into uppercase letters.
It returns a new string and does not change the original string.
Syntax
string_name.upper()
Example
print([Link]())
Output
PYTHON PROGRAMMING
Explanation: All lowercase characters in the string are converted into uppercase letters.
2. lower() Method
The lower() method converts all uppercase letters of a string into lowercase letters.
Syntax
string_name.lower()
Example
print([Link]())
Output
python programming
3. replace() Method
The replace() method is used to replace one substring with another substring in a string.
Syntax
string_name.replace(old, new)
Where:
Example
print([Link]("easy", "powerful"))
Output
Python is powerful
4. split() Method
Syntax
string_name.split(separator)
Example
print([Link](","))
Output
5. join() Method
The join() method is used to combine multiple strings into one string using a separator.
Syntax
[Link](sequence)
Example
print(joined_string)
Output
This is a list
Explanation: A space " " is inserted between each word and all words are combined into one string.
6. strip() Method
The strip() method removes spaces or unwanted characters from the beginning and end of a string.
Syntax
string_name.strip()
Example
print([Link]())
Output
Python
Explanation
7. find() Method
The find() method searches for a substring inside a string and returns its index position.
If the substring is not found, it returns -1.
Syntax
string_name.find(substring)
Example
print([Link]("Program"))
Output
Explanation
[Link] why Strings are immutable? Write the two reasons why string objects are made immutable in Python.
In Python, a string is a sequence of characters enclosed within single quotes, double quotes, or triple quotes. Strings are one
of the most commonly used data types in Python. An important feature of strings is that they are immutable.
word = "dollar"
word[0] = "c"
Output
Explanation
In the above program, Python gives an error because strings do not allow modification of characters using indexing.
word = "dollar"
print(new_word)
Output
collar
Explanation
Immutability makes strings safer because their values cannot be changed accidentally during program execution.
This helps maintain the correctness and reliability of data.
• passwords
• usernames
• file names
• keys in dictionaries
If strings were mutable, important data could be modified unintentionally, causing errors and security problems.
Example
password = "Admin123"
Example
s1 = "Python"
s2 = "Python"
print(id(s1))
print(id(s2))
Output
Explanation
Both variables point to the same memory location because the string value cannot be changed.
The elements in a list can be: numbers ,strings ,characters ,mixed data types ,other lists .
Lists are mutable, which means their elements can be changed after creation.
Syntax of List
Example of List
print(fruits)
Output
Syntax
list_name = []
Example
empty_list = []
print(empty_list)
Output
[]
A list can be created by placing elements inside square brackets separated by commas.
Example
print(numbers)
Output
print(mixed_list)
Output
Syntax
list_name = list(iterable)
Example
letters = list("Python")
print(letters)
Output
The range() function generates a sequence of numbers, and list() converts it into a list.
Syntax
Example
print(numbers)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(even_numbers)
Output
[2, 4, 6, 8, 10]
Example
print(nested_list)
Output
Example
numbers = []
for i in range(3):
value = int(input("Enter number: "))
[Link](value)
print(numbers)
Example
fruit_list = [Link]()
print(fruit_list)
Output
Python allows several operations to be performed on lists. These operations help in accessing, combining, modifying, and
processing list elements easily.
2. Repetition
3. Membership Operators
4. List Comparison
5. Indexing
6. Slicing
7. Traversing Lists
1. Concatenation (+)
Syntax
list1 + list2
Example
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2)
Output
[1, 2, 3, 4, 5, 6]
Explanation: The elements of list1 and list2 are combined into a new list.
2. Repetition (*)
Syntax
list * number
Example
numbers = [1, 2, 3]
print(numbers * 3)
Output
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Explanation
Python provides:
• in
• not in
Syntax
element in list
Example
print(20 in numbers)
print(50 in numbers)
Output
True
False
Explanation
The not in operator checks whether an element is absent from the list.
Example
Output
True
Explanation
4. List Comparison
• ==
• !=
• <
• >
• <=
• >=
Example
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [4, 5, 6]
print(list1 == list2)
print(list1 != list3)
Output
True
True
Explanation
5. Indexing
Syntax
list_name[index]
Example
print(colors[0])
print(colors[1])
print(colors[-1])
Output
red
green
blue
Explanation
6. Slicing
Syntax
list_name[start:stop]
Where:
Example 1
print(numbers[1:4])
Output
Syntax
list_name[start:stop:step]
Example 2
numbers = [1, 2, 3, 4, 5, 6]
print(numbers[0:6:2])
Output
[1, 3, 5]
Explanation
7. Traversing a List
Syntax
Example
Output
apple
banana
mango
Explanation: The loop takes one element at a time from the list and prints it.
A list is an ordered and mutable collection of elements enclosed within square brackets [ ].
In Python, elements of a list can be accessed using indexing and slicing. These operations help in retrieving individual
elements or extracting parts of a list easily.
Indexing and slicing are very important operations performed on lists in Python programming.
1. Indexing on Lists
Indexing is used to access individual elements of a list using their position number.
• Last element → -1
Syntax of Indexing
list_name[index]
Where:
print(colors[0])
print(colors[1])
print(colors[2])
Output
red
green
blue
Explanation
Negative Indexing
Negative indexing is used to access elements from the end of the list.
Example
print(numbers[-1])
print(numbers[-2])
print(numbers[-3])
Output
50
40
30
Explanation
Example
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)
Output
Explanation
2. Slicing on Lists
list_name[start:stop]
Where:
print(numbers[1:4])
Output
Explanation
print(numbers[:3])
Output
Explanation
print(numbers[2:])
Output
Syntax
list_name[start:stop:step]
Example
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
print(numbers[0:8:2])
Output
[1, 3, 5, 7]
Explanation
Example
print(numbers[-4:-1])
Output
Explanation
Example
numbers = [1, 2, 3, 4, 5]
print(numbers[::-1])
Output
[5, 4, 3, 2, 1]
Explanation
Python provides several built-in functions that can be used on lists. These functions help in performing operations such as
finding the length of the list, calculating values, sorting elements, and checking conditions. Built-in functions make list
handling easy and efficient.
1. len()
2. sum()
3. max()
4. min()
5. sorted()
6. any()
7. all()
1. len() Function
The len() function is used to find the number of elements present in a list.
Syntax
len(list_name)
Example
print(len(numbers))
Output
Explanation
2. sum() Function
The sum() function is used to calculate the total sum of all numeric elements in a list.
Syntax
sum(list_name)
Example
print(sum(numbers))
Output
100
Explanation
The function adds all elements:
10 + 20 + 30 + 40 = 100
3. max() Function
Syntax
max(list_name)
Example
print(max(numbers))
Output
45
Explanation
4. min() Function
Syntax
min(list_name)
Example
print(min(numbers))
Output
5. sorted() Function
The sorted() function is used to sort the elements of a list in ascending order.
It returns a new sorted list.
Syntax
sorted(list_name)
Example
print(sorted(numbers))
Output
print(sorted(numbers, reverse=True))
Output
6. any() Function
The any() function returns True if at least one element in the list is true.
Syntax
any(list_name)
Example
print(any(values))
Output
True
Explanation
7. all() Function
The all() function returns True only if all elements in the list are true.
Syntax
all(list_name)
Example
values = [1, 2, 3]
print(all(values))
Output
True
Explanation
All elements are non-zero and true values, so the result is True.
[Link] any five List methods with syntax and their purpose.
List methods are very important because lists are mutable, which means their contents can be changed after creation.
1. append()
2. insert()
3. remove()
4. pop()
5. sort()
Additional useful methods:
6. extend()
7. reverse()
1. append() Method
The append() method is used to add an element at the end of the list.
Syntax
list_name.append(element)
Example
[Link](40)
print(numbers)
Output
Purpose
2. insert() Method
The insert() method is used to insert an element at a specified position in the list.
Syntax
list_name.insert(index, element)
Where:
Example
[Link](1, "green")
print(colors)
Output
Purpose
3. remove() Method
The remove() method is used to delete a specified element from the list.
Syntax
list_name.remove(element)
Example
[Link](20)
print(numbers)
Output
Purpose
4. pop() Method
The pop() method removes and returns an element from the list.
If no index is specified, it removes the last element.
Syntax
list_name.pop(index)
[Link]()
print(numbers)
Output
[Link](1)
print(numbers)
Output
Purpose
5. sort() Method
Syntax
list_name.sort()
Example
numbers = [40, 10, 30, 20]
[Link]()
print(numbers)
Output
Purpose
[Link](reverse=True)
print(numbers)
Output
The extend() method is used to add elements of one list to another list.
Syntax
[Link](list2)
Example
list1 = [1, 2, 3]
list2 = [4, 5, 6]
[Link](list2)
print(list1)
Output
[1, 2, 3, 4, 5, 6]
Purpose
Syntax
list_name.reverse()
Example
numbers = [1, 2, 3, 4]
[Link]()
print(numbers)
Output
[4, 3, 2, 1]
Purpose
A dictionary is an unordered collection of elements stored in the form of key:value pairs enclosed within curly braces { }.
In a dictionary:
Dictionaries are mutable, which means their elements can be modified after creation.
Features of Dictionary
Syntax of Dictionary
dictionary_name = {
key1 : value1,
key2 : value2,
key3 : value3
}
Example of Dictionary
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}
print(student)
Output
Explanation
A dictionary can be created by directly placing key:value pairs inside curly braces.
Syntax
Example
print(my_dict)
Output
Explanation
Syntax
dict([**kwarg])
Example
print(numbers)
Output
Explanation: The keyword arguments one=1, two=2, and three=3 are converted into key:value pairs.
Syntax
dict(iterable)
Example
print(student)
Output
Explanation: Each tuple inside the list becomes a key:value pair in the dictionary.
Syntax
dictionary_name = {}
Example
countries = {}
print(countries)
Output
{}
One common way of creating dictionaries is to start with an empty dictionary and then use the update() method to add
key:value pairs.
Example
countries = {}
[Link]({"Asia":"India"})
[Link]({"Europe":"Germany"})
[Link]({"Africa":"Sudan"})
print(countries)
Output
Explanation: The update() method adds new key:value pairs to the dictionary.
Example
build_dictionary = {}
build_dictionary["name"] = "Ravi"
build_dictionary["course"] = "BCA"
print(build_dictionary)
Output
Explanation
• If the key does not exist, Python automatically creates the key:value pair.
Example
build_dictionary = {}
build_dictionary.update({dic_key: dic_val})
print(build_dictionary)
Sample Output
Enter key: a
Enter value: 1
Enter key: b
Enter value: 2
Explanation: The user enters keys and values, which are added dynamically to the dictionary.
1. len()
2. dict()
3. str()
1. len() Function
The len() function is used to find the number of key:value pairs present in a dictionary.
Syntax
len(dictionary_name)
Example
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}
print(len(student))
Output
Explanation: The dictionary contains three key:value pairs, so the function returns 3.
2. dict() Function
Syntax
dict([**kwarg])
OR
dict(iterable)
print(numbers)
Output
print(student)
Output
Explanation
3. str() Function
Syntax
str(dictionary_name)
Example
student = {
"name": "Ravi",
"age": 20
}
result = str(student)
print(result)
print(type(result))
Output
Syntax
type(object)
Example
student = {
"name": "Ravi",
"age": 20
}
print(type(student))
Output
<class 'dict'>
Explanation: The function shows that the object belongs to dictionary datatype.
The sorted() function sorts the keys of the dictionary in ascending order.
Syntax
sorted(dictionary_name)
Example
student = {
"course": "BCA",
"age": 20,
"name": "Ravi"
}
print(sorted(student))
Output
[Link] any five Dictionary methods with syntax and their purpose.
Since dictionaries are mutable, these methods are very useful in dictionary manipulation and data processing.
1. keys()
2. values()
3. items()
4. update()
5. get()
1. keys() Method
The keys() method returns all the keys present in the dictionary.
Syntax
dictionary_name.keys()
Example
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}
print([Link]())
Output
Purpose
2. values() Method
The values() method returns all the values present in the dictionary.
Syntax
dictionary_name.values()
Example
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}
print([Link]())
Output
Purpose
3. items() Method
The items() method returns both keys and values together in tuple form.
Syntax
dictionary_name.items()
Example
student = {
"name": "Ravi",
"age": 20
}
print([Link]())
Output
Purpose
• Returns key:value pairs together
4. update() Method
The update() method is used to add new key:value pairs or modify existing values in a dictionary.
The document also uses this method while populating dictionaries.
Syntax
dictionary_name.update({key:value})
Example
student = {
"name": "Ravi",
"age": 20
}
[Link]({"course":"BCA"})
print(student)
Output
student = {
"name": "Ravi",
"age": 20
}
[Link]({"age":21})
print(student)
Output
Purpose
5. get() Method
The get() method returns the value associated with a specified key.
It avoids errors if the key is not present.
Syntax
dictionary_name.get(key)
Example
student = {
"name": "Ravi",
"age": 20
}
print([Link]("name"))
Output
Ravi
Explanation: The method returns the value associated with the key "name".
The pop() method removes the specified key and returns its value.
Syntax
dictionary_name.pop(key)
Example
student = {
"name": "Ravi",
"age": 20
}
[Link]("age")
print(student)
Output
{'name': 'Ravi'}
Purpose
Syntax
dictionary_name.clear()
Example
student = {
"name": "Ravi",
"age": 20
}
[Link]()
print(student)
Output
{}
Purpose
Accessing means retrieving the value associated with a specific key in a dictionary.
Syntax
dictionary_name[key]
Example
student = {'name': 'John', 'age': 20, 'city': 'New York'} print(student['name']) print(student['age'])
Output:
John 20
Explanation
• The values are accessed by placing the key inside square brackets
The get() method is used to access values without causing an error if the key is missing.
Syntax
[Link](key, default_value)
Example
Output:
Modifying means changing the value of an existing key or adding a new key:value pair.
Syntax
dictionary_name[key] = value
Example
student['age'] = 25 print(student)
Output:
Example
Output:
{'name': 'John', 'age': 25, 'city': 'New York', 'course': 'BCA'}
Explanation
The update() method is used to add or modify multiple key:value pairs at once.
Syntax
[Link](other_dictionary)
Example
Output:
{'name': 'John', 'age': 30, 'city': 'New York', 'course': 'BCA', 'country': 'USA'}
Important Points
Accessing and modifying key:value pairs are fundamental operations in dictionaries. Using indexing, get(), and update()
methods, we can efficiently retrieve and update data. This makes dictionaries very useful for storing and managing structured
data
• items() method
• for loop
The items() method returns both keys and values together in tuple form, which makes traversal easy and efficient.
Traversing means visiting every element of the dictionary one after another.
In dictionaries:
• items() method
• for loop
(key, value)
Where:
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}
Output
name : Ravi
age : 20
course : BCA
Explanation
employee = {
"id": 101,
"name": "Anil",
"salary": 25000
}
Output
id = 101
name = Anil
salary = 25000
Explanation: The loop traverses every key:value pair in the dictionary and prints them.
The document also explains that the keys() method returns all keys of a dictionary.
Syntax
for key in dictionary_name.keys():
print(key)
Example
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}
Output
name
age
course
The document also includes the values() method, which returns all dictionary values.
Syntax
Example
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}
Output
Ravi
20
BCA
Populating dictionaries is very important because dictionaries are mutable and allow dynamic insertion of data.
In a dictionary:
Syntax of Dictionary
dictionary_name = {
key1:value1,
key2:value2
}
The simplest way is to add key:value pairs while creating the dictionary.
Example
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}
print(student)
Output
Explanation
Dictionary elements can be added dynamically using keys and assignment operator.
Syntax
dictionary_name[key] = value
Example
student = {}
student["name"] = "Ravi"
student["age"] = 20
student["course"] = "BCA"
print(student)
Output
The document explains the use of update() method for populating dictionaries.
The update() method inserts new key:value pairs into the dictionary.
Syntax
dictionary_name.update({key:value})
Example
countries = {}
[Link]({"Asia":"India"})
[Link]({"Europe":"Germany"})
[Link]({"Africa":"Sudan"})
print(countries)
Output
Explanation
The document also demonstrates populating dictionaries dynamically using loops and user input.
Example
build_dictionary = {}
build_dictionary.update({dic_key: dic_val})
print(build_dictionary)
Sample Output
Explanation
print(student)
Output
print(student)
Output
If a key already exists, the new value replaces the old value.
Example
student = {
"name": "Ravi",
"age": 20
}
student["age"] = 21
print(student)
Output
A tuple is one of the built-in data types in Python used to store multiple values in a single [Link] is an ordered
collection of elements enclosed within parentheses ( ). Tuples are similar to lists, but tuples are immutable, meaning their
elements cannot be modified after creation.
• integers
• strings
• floating point values
• mixed datatypes
tuples support:
• indexing
• slicing
Features of Tuple
Syntax of Tuple
Example of Tuple
print(student)
Output
Syntax
tuple_name = ()
Example
empty_tuple = ()
print(empty_tuple)
Output
()
Example
print(numbers)
Output
print(mixed_tuple)
Output
Explanation
The document explains that parentheses are optional while creating tuples.
If elements are separated by commas, Python automatically treats them as tuples.
Example
print(colors)
Output
Explanation
For a single element tuple, a comma must be placed after the element.
Without comma, Python treats it as a normal value.
Syntax
tuple_name = (element,)
Example
single_tuple = (10,)
print(single_tuple)
print(type(single_tuple))
Output
(10,)
<class 'tuple'>
value = (10)
print(type(value))
Output
<class 'int'>
Explanation
The document also includes creation of tuples using the built-in tuple() function.
Syntax
tuple(iterable)
print(numbers)
Output
(1, 2, 3, 4)
letters = tuple("Python")
print(letters)
Output
Example
print(nested_tuple)
Output
Example
numbers = []
for i in range(3):
value = int(input("Enter number: "))
[Link](value)
result = tuple(numbers)
print(result)
Explanation
Example
print(colors[0])
print(colors[1])
Output
red
green
Immutability of Tuple
According to the document, tuples are immutable, meaning their values cannot be changed after creation.
Example
# numbers[1] = 50
Explanation
Advantages of Tuple
1. Indexing
2. Slicing
These operations help in retrieving individual elements or extracting parts of a tuple easily.
1. Indexing on Tuple
Indexing is used to access individual elements of a tuple using their position number.
Python also supports negative indexing, where counting starts from the end.
• Last element → -1
Syntax of Indexing
tuple_name[index]
Where:
print(colors[0])
print(colors[1])
print(colors[2])
Output
red
green
blue
Explanation
Negative indexing is used to access elements from the end of the tuple.
Example
print(numbers[-1])
print(numbers[-2])
print(numbers[-3])
Output
50
40
30
Explanation
Example
# numbers[1] = 50
Explanation: Python generates an error because tuples do not support item assignment.
2. Slicing on Tuple
tuple_name[start:stop]
Where:
print(numbers[1:4])
Output
Explanation
print(numbers[:3])
Output
Explanation
print(numbers[2:])
Output
Explanation
Syntax
tuple_name[start:stop:step]
Example
numbers = (1, 2, 3, 4, 5, 6, 7, 8)
print(numbers[0:8:2])
Output
(1, 3, 5, 7)
Example
print(numbers[-4:-1])
Output
Example
numbers = (1, 2, 3, 4, 5)
print(numbers[::-1])
Output
(5, 4, 3, 2, 1)
[Link] the different built-in functions and methods in tuple. Explain with example.
A tuple is an ordered and immutable collection of elements enclosed within parentheses ( ).
Since tuples are immutable, only a few methods are available for tuples compared to lists. However, Python provides several
built-in functions that can be used on tuples.
• performing calculations
• counting elements
• searching values
The important built-in functions and methods used with tuples are:
Built-in Functions
1. len()
2. max()
3. min()
4. sum()
5. tuple()
6. sorted()
Tuple Methods
1. count()
2. index()
1. len() Function
The len() function is used to find the number of elements present in a tuple.
Syntax
len(tuple_name)
Example
print(len(numbers))
Output
2. max() Function
Syntax
max(tuple_name)
Example
print(max(numbers))
Output
45
3. min() Function
Syntax
min(tuple_name)
Example
print(min(numbers))
Output
Explanation: The function returns the minimum element from the tuple.
4. sum() Function
The sum() function calculates the total sum of numeric elements in the tuple.
Syntax
sum(tuple_name)
Example
print(sum(numbers))
Output
100
Explanation
5. tuple() Function
The tuple() function is used to create a tuple from another iterable object.
Syntax
tuple(iterable)
Example
letters = tuple("Python")
print(letters)
Output
6. sorted() Function
The sorted() function sorts tuple elements and returns them as a list.
Syntax
sorted(tuple_name)
Example
print(sorted(numbers))
Output
Explanation: The tuple elements are arranged in ascending order and returned as a list.
Tuple Methods
Tuples provide only two built-in methods because tuples are immutable.
1. count() Method
The count() method returns the number of times a specified element occurs in the tuple.
Syntax
tuple_name.count(element)
Example
print([Link](10))
Output
2. index() Method
The index() method returns the index position of the first occurrence of the specified element.
Syntax
tuple_name.index(element)
Example
print([Link](30))
Output
Since tuples are immutable, their elements cannot be modified after creation.
However, several operations can still be performed on tuples efficiently.
The important basic operations performed on tuples are:
1. Accessing Elements
2. Indexing
3. Slicing
4. Concatenation
5. Repetition
6. Membership Operations
7. Iteration or Traversal
8. Length Operation
Python supports:
• Positive indexing
• Negative indexing
Syntax
tuple_name[index]
Example
print(colors[0])
print(colors[1])
Output
red
green
Explanation
2. Indexing Operation
Python follows:
print(numbers[-1])
print(numbers[-2])
Output
40
30
Explanation
3. Slicing Operation
Syntax
tuple_name[start:stop]
Example
print(numbers[1:4])
Output
Explanation
numbers = (1, 2, 3, 4, 5, 6)
print(numbers[0:6:2])
Output
(1, 3, 5)
4. Concatenation Operation
Syntax
tuple1 + tuple2
Example
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
print(result)
Output
(1, 2, 3, 4, 5, 6)
5. Repetition Operation
Syntax
tuple_name * n
Example
numbers = (1, 2, 3)
print(numbers * 3)
Output
(1, 2, 3, 1, 2, 3, 1, 2, 3)
6. Membership Operation
Membership operators are used to check whether an element exists in the tuple.
Python provides:
• in
• not in
Example using in
print(20 in numbers)
Output
True
Output
True
Explanation
Traversal means accessing each element of the tuple one by one using loops.
Syntax
Example
Output
red
green
blue
8. Length Operation
The len() function returns the total number of elements in the tuple.
Syntax
len(tuple_name)
Example
print(len(numbers))
Output
Tuples are immutable, so operations like insertion, deletion, and modification are not allowed.
Example
# numbers[1] = 50
Unlike lists and dictionaries, tuples are immutable, so elements cannot be added, removed, or modified after the tuple is
created. Therefore, tuples are populated only during creation or by creating a new tuple.
• integers
• strings
• mixed datatypes
4. By concatenating tuples
Since tuples are immutable, direct insertion after creation is not allowed.
Syntax of Tuple
Example
print(student)
Output
Explanation
• 20 → second element
Example
print(mixed_tuple)
Output
Explanation
• Integer
• String
• Float
• Boolean value
The built-in tuple() function is used to create and populate tuples from iterable objects.
Syntax
tuple(iterable)
print(numbers)
Output
letters = tuple("Python")
print(letters)
Output
Explanation
Example
numbers = []
for i in range(3):
result = tuple(numbers)
print(result)
Sample Output
Enter number: 10
Enter number: 20
Enter number: 30
Explanation
Since tuples are immutable, new elements can be added by concatenating tuples.
Example
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
print(result)
Output
(1, 2, 3, 4, 5)
Explanation
Example
print(nested_tuple)
Output
Explanation
Example
# numbers[1] = 50
Explanation
Example
print(colors[0])
print(colors[1])
Output
red
green
[Link] are set ? Explain with example any five set methods .
A set is one of the built-in data types in Python used to store multiple elements in a single variable.
A set is an unordered collection of unique elements enclosed within curly braces { }.
Sets are mutable, which means elements can be added or removed after creation.
Definition of Set
A set is an unordered collection of unique elements enclosed within curly braces { }.
Features of Set
Syntax of Set
Example of Set
print(numbers)
Output
Explanation: The elements may appear in different order because sets are unordered.
print(numbers)
Output
1. add()
2. update()
3. remove()
4. discard()
5. pop()
Additional methods:
• clear()
• union()
• intersection()
1. add() Method
Syntax
set_name.add(element)
Example
[Link](40)
print(numbers)
Output
Explanation
2. update() Method
Syntax
set_name.update(iterable)
Example
print(numbers)
Output
Explanation
3. remove() Method
Syntax
set_name.remove(element)
Example
[Link](20)
print(numbers)
Output
Explanation
Important Point
4. discard() Method
Syntax
set_name.discard(element)
Example
[Link](20)
print(numbers)
Output
{10, 30}
5. pop() Method
Syntax
set_name.pop()
Example
Example
Output: set()
union() Method
Example
A = {1, 2, 3}
B = {3, 4, 5}
print([Link](B))
Output
{1, 2, 3, 4, 5}
intersection() Method
Example
A = {1, 2, 3}
B = {2, 3, 4}
print([Link](B))
Output: {2, 3}