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

Unit 2 Python

The document provides an overview of various Python concepts including strings, lists, dictionaries, and tuples. It explains methods for creating and manipulating these data types, including string slicing, list indexing, and dictionary key-value access. Additionally, it covers built-in functions and operations such as concatenation, repetition, and membership checks.

Uploaded by

pujarinidhi3
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 views16 pages

Unit 2 Python

The document provides an overview of various Python concepts including strings, lists, dictionaries, and tuples. It explains methods for creating and manipulating these data types, including string slicing, list indexing, and dictionary key-value access. Additionally, it covers built-in functions and operations such as concatenation, repetition, and membership checks.

Uploaded by

pujarinidhi3
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
You are on page 1/ 16

2m

1. Give two methods of creating strings in Python.


>>> single_quote = 'This is a single message'
>>> double_quote = "Hey it is my book"
>>> single_char_string = "A"

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?

As strings are immutable, it cannot be modified. The characters in a string cannot be


changed once a stri ng value is assigned to string variable. However, you can assign differ ent
string values to the same string variable.
4. What is use of negative indexing? Give example.
negative indexing can be useful for a variety of tasks, such as reversing a list, removing the last
element from a list, or finding the index of an element in a list. Negative indexing is a way of
accessing elements in a list, string, or other sequence from the end of the sequence instead of the
beginning. In Python, negative indexes start at -1 for the last element, -2 for the second-to-last
element, and so on.

Eg: list = [1, 2, 3, 4, 5]

print(list[-1]) #5

5. Give the output of the following Python code:


str1 = 'This is Python'

print( "Slice of String : ", str1[1 : 4 : 1] )


print ("Slice of String : ", str1[0 : -1 : 2] )
Slice of String: his
Slice of String: Ti sPto
6. Give the output of following Python code
newspaper = "new york times"

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]])

Eg: watches = "rolex hublot cartier omega"


watches.split()
[’rolex’, ’hublot’, ’cartier’, ’omega’]
8. Write Python code to print each character in a string.
def print_characters(string):

for character in string:


print(character)
string = "Hello, world!"
print_characters(string)
9. What is list? How to create list ?

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)

print ("Final List:", aList)


output: Final List: [123, 'xyz', 'zara', 2009, 'abc']
12.Give the syntax and example for list slicing
Syntax: list_name[strat:stop[:step]]
Eg: fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]
fruits[1:3]
# ['pineapple', 'blueberries']
13. What is dictionary? Give example

Dictionaries are used to store data values in key:value pairs.


A dictionary is a collection which is ordered*, changeable and do not allow duplicates
Eg: thisdict = {
"brand": "Ford",
"model": "Mustang",

"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.

Syntax: dictionary_name[key] = value


Eg: student = {"name": "Alice", "age": 20, "grade": "A"}
student["age"] = 21
print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A'}
15.List any four built-in functions used on dictionary

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():

print(key, ":", value)


# name : Alice
age : 20
grade : A
17.What is tuple ? How it is created in Python

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)

19.Give syntax and purpose of two built-in functions used on tuples


len(): The len() function returns the numbers of items in a tuple.
Syntax: len(tuple)
sum() :The sum() function returns the sum of numbers in the tuple.
Syntax: sum(tuple)

sorted() :The sorted() function returns a sorted copy of the tuple as a list while leaving the
original tuple untouched.

20.How to convert tuple in to List ? Give example`


To convert a tuple into a list in Python, you can use the list() function. The list() function
takes an iterable as an argument and returns a new list containing the elements of the
iterable. Here's an example:
my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3, 4, 5]
21.Differentiate tuple and set datatype
Feature Tuple Set

Order Ordered Unordered


Duplication Not allowed Allowed
Mutability Immutable Mutable
Eg Example: (1, 2, 3) Example: {1, 2, 3} or set([1, 2, 3])
22.List any two set methods and mention purpose of each method.

add() : The add() method adds an item to the set set_name.


remove():The method remove() removes an item from the set set_name.
4m:
1. What is string slicing? Explain with examples
string slicing is a way to extract a substring from a string. It is done by specifying the start
and end indices of the substring, and the step size. The start index is the position of the first
character you want to include in the substring, and the end index is the position of the
character after the last character you want to include in the substring. The step size specifies
how many characters to skip between each character in the substring
The syntax for string slicing is: string[start:end:step]
Eg: my_string = "Hello, World!"
slice_1 = my_string[7:12]

slice_2 = my_string[0:5:2]
print(slice_1) # Output: World
print(slice_2) # Output: Hlo

eg2: my_string = "Python Programming"

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"

substring = string[-5:-1:2] # "or"


3. Explain split and join methods of string with example.
the split() and join() methods are two of the most commonly used string methods in Python.
The split() method splits a string into a list of substrings, while the join() method joins a list
of strings into a single string.
The split() method takes a separator as its argument, and it splits the string at the
occurrences of the separator.
Eg: string = "hello world"
substrings = string.split(" ")
print(substrings) #['hello', 'world']

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’

repetiton: repetition_of_string = "wow" * 5


repetition_of_string
output: ’wowwowwowwowwow’
membership:You can check for the presence of an item in the list using in and not in
membership operators. It returns a Boolean True or False. For example,
fruit_string = "apple is a fruit"
fruit_sub_string = "apple"

fruit_sub_string in fruit_string
True
another_fruit_string = "orange"
another_fruit_string not in fruit_string
True

5. Explain any five string functions with syntax and example.


Lower ,upper: The lower() method returns a string where all characters are lower case.
Syntax :string.lower()
Eg:txt = "Hello my FRIENDS"
x = txt.lower()

print(x) #hello my friends


islower() :method returns True if all the characters are in lower case, otherwise False.
Syntax: string.islower()
Eg:txt = "hello world!"
x = txt.islower()

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

6. Write a note on indexing and slicing lists.


Indexing:
 Indexing allows you to access individual elements in a list using their position or
index.
 The index of the first element in a list is 0, the second element is 1, and so on.
 Negative indices can also be used, where -1 refers to the last element, -2 refers to the
second-to-last element, and so forth.
 Syntax: list[index]

Eg: my_list = [10, 20, 30, 40, 50]


print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30
print(my_list[-1]) # Output: 50
if a example is string => syntax: string_name[index]

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]

print(my_list[2:]) # Output: [30, 40, 50]


print(my_list[::2]) # Output: [10, 30, 50]
print(my_list[::-1]) # Output: [50, 40, 30, 20, 10]
7. Explain any five list methods with syntax.
remove():The remove() method searches for the first instance of the given

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

8. Write a Python code to implement stack operations using lists

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

print(student['gpa']) # Output: 3.8


# Modifying values by key
student['age'] = 21
student['gpa'] = 4.0
if 'name' in student:

print(student['name']) # Output: John


print(student['age']) # Output: 21
print(student['gpa']) # Output: 4.0
12.Explain any five dictionary methods with syntax.
clear():The clear() method removes all the key:value pairs from the dictionary.
dictionary_name.clear()
update():The update() method updates the dictionary with the key:value pairs from other
dictionary object and it returns None
dictionary_name. update([other])

. 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

print("Final Dictionary:", my_dict)


output:
Enter the number of key-value pairs: 3
Enter key: name
Enter value: John

Enter key: age


Enter value: 25
Enter key: city
Enter value: New York

Final Dictionary: {'name': 'John', 'age': '25', 'city': 'New York'}


14.Explain with example how to traverse dictionary using key:value pair
To traverse a dictionary using key-value pairs in Python, you can use the items() method. This
method returns a view object that contains the key-value pairs of the dictionary, allowing
you to iterate over them.
# Create a dictionary
student = {
'name': 'John',

'age': 20,
'major': 'Computer Science',
'gpa': 3.8
}
# Traverse dictionary using key-value pairs

for key, value in student.items():


print(key, ":", value)
output:
name : John
age : 20

major : Computer Science


gpa : 3.8
15.Write a note on indexing and slicing tuples
Indexing:
 Tuples are ordered collections, and each element in a tuple has a unique index.

 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')

print(my_tuple[2:]) # Output: ('cherry', 'date')


16. Write a Python program to populate tuple with user input data.
my_tuple = ()
num_elements = int(input("Enter the number of elements: "))
# Iterate based on the number of elements

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:

Enter the number of elements: 4


Enter element: apple
Enter element: banana
Enter element: cherry
Enter element: date

Final Tuple: ('apple', 'banana', 'cherry', 'date')


17.Explain any Five set methods
add(): set_name.add(item)
The add() :method adds an item to the set set_name.

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"}

american_flowers.add("orchids") #{'roses', 'lilies', 'tulips', 'daisies', 'orchids'}

print(american_flower)
american_flowers.clear() #set()

american_flowers.pop() #{'roses', 'daisies', 'lilies'}

american_flowers.discard("roses") #{'daisies', 'lilies', 'tulips'}

american_flowers.issuperset(european_flowers) # False

american_flowers.issubset(european_flowers) #False

You might also like