Unit 2 Python
Unit 2 Python
2. List any two built in functions used with python strings. Mention their use.
len() :The len() function calculates the number of characters in a string.
max(): The max() function returns a character having highest ASCII value.
min() :The min() function returns character having lowest ASCII value.
3. Why strings are called immutable?
print(list[-1]) #5
print(newspaper[0:12:4])
print (newspaper[::4])
ny
ny e
7. Give the syntax and example for split function.
Syntax: string_name.split([separator [, maxsplit]])
ists are used to store multiple items in a single variable. list is a data structure that can store
a collection of values.
Lists are created using square brackets []. The elements of a list can be separated by commas
Eg: my_list = [10, 20, 30]
10.List any four built-in functions used on list.
len(): The len() function returns the numbers of items in a list.
sum() :The sum() function returns the sum of numbers in the list.
any(): The any() function returns True if any of the Boolean values in the list is True.
all() :The all() function returns True if all the Boolean values in the list are True, else
returns False.
11.aList = [123, 'xyz', 'zara', 'abc'];
aList.insert (3,2009)
"year": 1964
}
print(thisdict)
#{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
14.How to access and modify key value pairs of dictionary ?
Accessing Dictionary Values: To access the value associated with a specific key in a
dictionary, you can use square bracket notation or the get() method.
Syntax: dictionary_name[key]
Eg: student = {"name": "Alice", "age": 20, "grade": "A"}
print(student["name"]) # Output: Alice
print(student["age"]) # Output: 20
To modify the value associated with a specific key in a dictionary, you can use square bracket
notation to assign a new value to the key.
len(): The len() function returns the number of items (key:valuepairs) in a dictionary.
all(): The all() function returns Boolean True value if all the keys in the dictionary are True
else returns False.
any() :The any() function returns Boolean True value if any of the key in the dictionary is True
else returns False.
sorted() :The sorted() function by default returns a list of items, which are sorted based on
dictionary keys.
16.Write a Python code to Traversing of key:value Pairs in Dictionaries
student = {"name": "Alice", "age": 20, "grade": "A"}
for key, value in student.items():
Tuples are used to store multiple items in a single variable. Tuples can store elements of
different data types, such as integers, strings, floats, etc.
a tuple is an immutable sequence or ordered collection of elements, enclosed in
parentheses () or created without any enclosing parentheses.
tuple_name = (item_1, item_2, item_3, ………….., item_n)
eg: my_tuple = (10, 20, 30)
18.What is the output of print (tuple[1:3]) if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
Output: (786, 2.23)
sorted() :The sorted() function returns a sorted copy of the tuple as a list while leaving the
original tuple untouched.
slice_2 = my_string[0:5:2]
print(slice_1) # Output: World
print(slice_2) # Output: Hlo
slice_3 = my_string[7:]
slice_4 = my_string[:6]
print(slice_3) # Output: Programming
print(slice_4) # Output: Python
2. Write a note on negative indexing and slicing strings using negative indexing.
Negative indexing is a way to access elements in a string starting from the end of the string.
The index -1 refers to the last character in the string, -2 refers to the second-to-last
character, and so on. Eg:
string = "hello world"
print(string[-1]) #d
Slicing strings using negative indexing is similar to slicing strings using positive indexing,
except that you use negative indices to start slicing from the end of the string. For example,
the following code will extract the substring "world" from the string "hello world":
string = "hello world"
substring = string[-5:]
print(substring) #world
Here are some other examples of slicing strings using negative indexing:
string = "hello world"
substring = string[-5:-1] # "orld"
The join() method takes a sequence of strings as its argument, and it joins the strings
together using the separator as the delimiter.
Syntax: string_name.join(sequence)
Eg: substrings = ["hello", "world"]
string = " ".join(substrings)
print(string) #hello world
4. Explain concatenation , repetition and membership operations on string
Concatenation: concatenated_string_with_space = "Hi " + "There"
concatenated_string_with_space
output: ’Hi There’
fruit_sub_string in fruit_string
True
another_fruit_string = "orange"
another_fruit_string not in fruit_string
True
print(x) #true
isupper() :method returns True if all the characters are in upper case, otherwise False.
txt = "THIS IS NOW!"
x = txt.isupper()
print(x) #true
isnumeric(): method returns True if all the characters are numeric (0-9), otherwise False.
txt = "565543"
x = txt.isnumeric()
print(x) #true
isdigit(): method returns True if all the characters are digits, otherwise False.
txt = "50800"
x = txt.isdigit()
print(x) #true
eg2:my_list ="hello","star"
print(my_list[0]) #hello
Slicing:
Slicing allows you to extract a portion or a subsequence of elements from a list.
It is done by specifying a range of indices using the syntax list[start:end:step].
The start index is inclusive, the end index is exclusive, and the step determines the
increment between elements.
If not specified, start defaults to 0, end defaults to the length of the list, and step
defaults to 1.
Syntax: list[start:end:step]
Eg: my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # Output: [20, 30, 40]
print(my_list[:3]) # Output: [10, 20, 30]
item in the list and removes it. If the item is not present in the list then ValueError is thrown
by this method.
Syntax: list.remove(item)
sort():The sort() method sorts the items in place in the list. This method modifies the
original list and it does not return a new list.
Syntax: list.sort()
reverse():The reverse() method reverses the items in place in the list. This method modifies
the original list and it does not return a new list.
list.reverse()
append():The append() method adds a single item to the end of the list. This
method does not return new list and it just modifies the original.
list.append(item)
count():The count() method counts the number of times the item has occurred in the list
and returns it.
list.count(item)
insert():The insert() method inserts the item at the given index, shifting
items to the right.
list.insert(index, item)
eg: cities = ["oslo", "delhi", "washington", "london", "seattle", "paris", "washington"]
cities.count('seattle') #1
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def main():
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())
print(stack.pop())
print(stack.pop())
print(stack.is_empty())
if __name__ == "__main__":
main()
output: 3
3
2
False
9. Write a Python code to implement queue operations using lists
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
return self.queue.pop(0)
def peek(self):
return self.queue[0]
def is_empty(self):
return len(self.queue) == 0
def main():
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.peek())
print(queue.dequeue())
print(queue.dequeue())
print(queue.is_empty())
if __name__ == "__main__":
main()
output: 1
1
2
False
10.Write a note on nested lists.
A list inside another list is called a nested list and you can get the behavior of nested lists in
Python by storing lists within the elements of another list.
Eg: nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
11. With example explain how to Access and Modify key:value Pairs in Dictionaries
# Create a dictionary
student = {
'name': 'John',
'age': 20,
'major': 'Computer Science',
'gpa': 3.8
}
# Accessing values by key
print(student['name']) # Output: John
print(student['age']) # Output: 20
. values():The values() method returns a new view consisting of all the values in the
dictionary
dictionary_name. values()
items():The items() method returns a new view of dictionary’s key and value pairs as tuples.
dictionary_name. items()
keys():The keys() method returns a new view consisting of all the keys in the dictionary
dictionary_name. keys()
pop() : syntax: dictionary_name. pop(key[, default])
The pop() method removes the key from the dictionary and returns its value. If the key is not
present, then it returns the default value. If default is not given and the key is not in the
dictionary, then it results in KeyError
13.Write a Python Program to Dynamically Build dictionary using User Input as a List
my_dict = {}
num_pairs = int(input("Enter the number of key-value pairs: "))
# Iterate based on the number of pairs
for i in range(num_pairs):
key = input("Enter key: ")
value = input("Enter value: ")
my_dict[key] = value
# Print the final dictionary
'age': 20,
'major': 'Computer Science',
'gpa': 3.8
}
# Traverse dictionary using key-value pairs
Indexing allows you to access individual elements of a tuple using their position or
index.
The indexing in tuples starts from 0 for the first element, 1 for the second element,
and so on.
You can use square brackets [] with the index value to access a specific element of a
tuple.
Eg: my_tuple = ('apple', 'banana', 'cherry', 'date')
print(my_tuple[0]) # Output: 'apple'
print(my_tuple[2]) # Output: 'cherry'
Slicing:
Slicing allows you to extract a portion or subsequence of a tuple by specifying a range
of indices.
The syntax for slicing is start_index:end_index, where start_index is inclusive and
end_index is exclusive.
Slicing returns a new tuple that contains the selected elements from the original
tuple.
Eg: my_tuple = ('apple', 'banana', 'cherry', 'date')
print(my_tuple[1:3]) # Output: ('banana', 'cherry')
print(my_tuple[:2]) # Output: ('apple', 'banana')
for i in range(num_elements):
value = input("Enter element: ")
my_tuple += (value,) # Add the value to the tuple using concatenation
print("Final Tuple:", my_tuple)
output:
clear() :set_name.clear()
The clear() method removes all the items from the set set_name.
pop() :set_name.pop()
The method pop() removes and returns an arbitrary item from the set set_name. It raises
KeyError if the set is empty
discard() :set_name.discard(item)
The discard() method removes an item from the set set_name if it is present.
issubset(): set_name.issubset(other)
The issubset(): method returns True if every item in the set set_name is in other set.
issuperset() :set_name.issuperset(other)
The issuperset() method returns True if every element in other set is in the set set_name.
Eg: european_flowers = {"sunflowers", "roses", "lavender", "tulips", "goldcrest"}
american_flowers = {"roses", "tulips", "lilies", "daisies"}
print(american_flower)
american_flowers.clear() #set()
american_flowers.issuperset(european_flowers) # False
american_flowers.issubset(european_flowers) #False