0% found this document useful (0 votes)
5 views21 pages

Unit Ii

The document provides an overview of various data types and operations in Python, including strings, lists, dictionaries, and tuples. It explains concepts such as string immutability, negative indexing, list slicing, and dictionary key-value pairs, along with examples of built-in functions and methods for each data type. Additionally, it covers string manipulation techniques like concatenation, repetition, and membership operations.

Uploaded by

Sagar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views21 pages

Unit Ii

The document provides an overview of various data types and operations in Python, including strings, lists, dictionaries, and tuples. It explains concepts such as string immutability, negative indexing, list slicing, and dictionary key-value pairs, along with examples of built-in functions and methods for each data type. Additionally, it covers string manipulation techniques like concatenation, repetition, and membership operations.

Uploaded by

Sagar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT II

1. Give two methods of creating strings in Python.


Ans) >>> single_quote = 'This is a single message'
>>> double_quote = "Hey it is my book"
>>>triple_quote_string = '''This
… is
… triple
… quote'''
2. List any two built in functions used with python strings. Mention their use.
Ans)

3. Why strings are called immutable?


Ans) As strings are immutable, it cannot be modified. The characters in a string cannot be changed once a
string value is assigned to string variable. However, you can assign different string values to the same string
variable.
4. What is use of negative indexing? Give example.
Ans) The negative index can be used to access individual characters in a string. Negative indexing starts with
−1 index corresponding to the last character in the string and then the index decreases by one as we move to
the left.
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] )
Ans) 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])
Ans) ny
ny e
7. Give the syntax and example for split function.
Ans) The split() method returns a list of string items by breaking up the string using the delimiter string. The
syntax of split() method is,
string_name.split([separator [, maxsplit]])
eg:
1. >>> inventors = "edison, tesla, marconi, newton"
2. >>> inventors.split(",")
['edison', ' tesla', ' marconi', ' newton']
8. Write Python code to print each character in a string.
Ans)
alphabet = "google"
for each_char in alphabet:
print(f"Character : '{each_char}' ")
9. What is list? How to create list ?
Ans) A list is similar to an array that consists of a group of elements or items of different type.
create list:
 empty_list = []
 number_list = [4, 4, 6, 7, 2, 9, 10, 15]
 list1=list()

10.List any four built-in functions used on list.


Ans)

11.Write the output of the given python code :


aList = [123, 'xyz', 'zara', 'abc'];
aList.insert (3,2009)
print ("Final List:", aList)
Ans) Final List: [123, 'xyz', 'zara', 2009, 'abc']
12.Give the syntax and example for list slicing
Ans) Slicing of lists is allowed in Python wherein a part of the list can be extracted by specifying index range along
with the colon (:) operator which itself is a list. The syntax for list slicing is,

1. >>> fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]

2. >>> fruits[1:3]

['pineapple', 'blueberries']

3. >>> fruits[:3]

['grapefruit', 'pineapple', 'blueberries']

4. >>> fruits[2:]

['blueberries', 'mango', 'banana']

13. What is dictionary? Give example


Ans) A dictionary represents a group of elements arranged in the form of key-value pairs. In the dictionary, the first
element is considered as 'key' and the immediate next element is taken as its 'value'. The key and its value are
separated by a colon (:). All the key-value pairs in a dictionary are inserted in curly braces {}.

Let's take a dictionary by the name 'dict' that contains employee details:

Dict1 = {'Name': 'Chandra', 'Id': 200, 'Salary': 9080.50}

14.How to access and modify key value pairs of dictionary ?


Ans) The syntax for accessing the value for a key in the dictionary is,
dictionary_name[key]

eg: >>>dict1 = {'Name': 'Brinda', 'Id': 200, 'Salary': 9080.50}

>>>dict1['Name']

Brind

The syntax for modifying the value of an existing key or for adding a new key:value pair to a dictionary is,

dictionary_name[key] = value

eg: >>>dict1 = {'Name': 'Brinda', 'Id': 200, 'Salary': 9080.50}

>>>dict1['Name']=”Aravind”
>>>dict1

>>>={'Name': 'Aravind', 'Id': 200, 'Salary': 9080.50}

15.List any four built-in functions used on dictionary.


Ans)

16.Write a Python code to Traversing of key:value Pairs in Dictionaries

Ans:

colors = {'r': "Red", 'g': "Green", 'b': "Blue", 'w': "White"}

for k, v in colors.items():

print(f”Key= {k} Value= {v}”)

17.What is tuple ? How it is created in Python

Ans: A tuple stores a group of elements or items which is ordered and unchangeable. Since tuples are immutable,
once we create a tuple we cannot modify its elements. Tuples are similar to lists but the main difference is tuples are
immutable whereas lists are mutable.

Syntax for creating a tuple:

Eg:

Tup4 = (10, 20, -30.1, 40.5, 'Hyderabad', 'New Delhi')

tup1 = () #empty tuple

Tup2=tuple()

18.What is the output of print (tuple[1:3]) if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?

Ans: (786, 2.23)


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

Ans:

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

my_tuple = ('a', 'mm', 'ppp', 'bb', 'cc')

my_list = list(my_tuple)

print(my_list)

output : ['a', 'mm', 'ppp', 'bb', 'cc']

21.Differentiate tuple and set datatype.

 Tuple is an immutable sequence in python. It cannot be changed or replaced since it is immutable.


Where as set is mutable
 A set is an unordered collection of items in python. where as tuple is orderd collection of items In
python
 Curly braces { } or the set() function can be used to create sets with a comma-separated list of items
inside curly brackets { } where as () is used to create tuple with a comma-separated list of items
inside bracets().
 Tuple may have duplicate elements whereas set has no duplicate elements.
1. What is string slicing? Explain with examples
The "slice" syntax is a handy way to refer to sub-parts of sequence of characters within an original string.
The syntax for string slicing is,
string_name[start:end[:step]]
With string slicing, you can access a sequence of characters by specifying a range of index numbers
separated by a colon. String slicing returns a sequence of characters beginning at start and extending up to
but not including end. The start and end indexing values have to be integers. String slicing can be done using
either positive or negative indexing.

Eg:
>>> healthy_drink = "green tea"
>>> healthy_drink[0:3] 'gre'
>>> healthy_drink[:5] 'green'
>>> healthy_drink[6:] 'tea'
>>> healthy_drink[:] 'green tea'

1. >>> healthy_drink[-3:-1] 'te'


2. >>> healthy_drink[6:-1] 'te'
2. Write a note on negative indexing and slicing strings using negative indexing.
The negative index can be used to access individual characters in a string. Negative indexing starts with
−1 index corresponding to the last character in the string and then the index decreases by one as we move
to the left.

1. >>> healthy_drink[-3:-1]
'te'
2. >>> healthy_drink[6:-1]
'te'
>>> healthy_drink[-5]
n
>>> healthy_drink[-1]
a

You need to specify the lowest negative integer number in the start index position when using negative index
numbers as it occurs earlier in the string ➀. You can also combine positive and negative indexing numbers
➁.
3. Explain split and join methods of string with example.
The split() method returns a list of string items by breaking up the string using the delimiter string. The
syntax of split() method is,

Syntax: string_name.split([separator [, maxsplit]])

Here separator is the delimiter string and is optional. A given string is split into list of strings based on the
specified separator. If the separator is not specified then whitespace is considered as the delimiter string to
separate the strings. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most
maxsplit + 1 items). If maxsplit is not specified or −1, then there is no limit on the number of splits.

eg:
1. >>> inventors = "edison, tesla, marconi, newton"
2. >>> inventors.split(",")
['edison', ' tesla', ' marconi', ' newton']

join() method :Strings can be joined with the join() string. The join() method provides a flexible way to
concatenate strings. The syntax of join() method is, string_name.join(sequence) Here sequence can be string or list. If
the sequence is a string, then join() function inserts string_name between each character of the string sequence and
returns the concatenated string. If the sequence is a list, then join() function inserts string_name between each item
of list sequence and returns the concatenated string. It should be noted that all the items in the list should be of
string type.

1. >>> date_of_birth = ["17", "09", "1950"]

2. >>> ":".join(date_of_birth)

'17:09:1950'

3. >>> social_app = ["instagram", "is", "an", "photo", "sharing", "application"]

4. >>> " ".join(social_app)

'instagram is an photo sharing application’


4. Explain concatenation , repetition and membership operations on string.
In Python, strings can also be concatenated using + sign

* operator is used to create a repeated sequence of strings.

Concatenation:
1. >>> string_1 = "face"

2. >>> string_2 = "book"

3. >>> concatenated_string = string_1 + string_2

4. >>> concatenated_string

'facebook'

5. >>> concatenated_string_with_space = "Hi " + "There"

6. >>> concatenated_string_with_space

'Hi There'

Two string variables are assigned with "face"➀ and "book" ➁ string values. The string_1 and string_2 are
concatenated using + operator to form a new string. The new string concatenated_string ➃ has the values of both the
strings ➂. As you can see in the output, there is no space between the two concatenated string values. If you need
whitespace between concatenated strings ➅, all you need to do is include whitespace within a string like in ➄.

Repetition:

10. >>> repetition_of_string = "wow" * 5

11. >>> repetition_of_string

'wowwowwowwowwow'

You can use the multiplication operator * on a string ➉. It repeats the string the number of times you specify and the
string value “wow” is repeated five times .

member ship operators :You can check for the presence of a string in another string using in and not in member ship
operators. It returns either a Boolean True or False. The in operator evaluates to True if the string value in the left
operand appears in the sequence of characters of string value in right operand. The not in operator evaluates to True
if the string value in the left operand does not appear in the sequence of characters of string value in right operand.

1. >>> fruit_string = "apple is a fruit"

2. >>> fruit_sub_string = "apple"

3. >>> fruit_sub_string in fruit_string

True

4. >>> another_fruit_string = "orange"

5. >>> another_fruit_string not in fruit_string


True

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


capitalize() string_name.capitalize()

The capitalize() method returns a copy of the string with its first character capitalized and the rest lowercased.

endswith() string_name.endswith(suffix[, start[, end]])

This method endswith(), returns True if the string_name ends with the specified suffix substring, otherwise returns
False. With optional start, test beginning at that position. With optional end, stop comparing at that position

startswith() string_name.startswith(prefix[, start[, end]])

The method startswith() returns Boolean True if the string starts with the prefix, otherwise return False. With
optional start, test string_name beginning at that position. With optional end, stop comparing string_ name at that
position.

istitle() string_name.istitle()

The method istitle() returns Boolean True if the string is a title cased string and there is at least one character, else it
returns Boolean False.

isupper() string_name.isupper()

The method isupper() returns Boolean True if all cased characters in the string are uppercase and there is at least one
cased character, else it returns Boolean False.

islower() string_name.islower()

The method islower() returns Boolean True if all characters in the string are lowercase, else it returns Boolean False.

upper() string_name.upper()

The method upper() converts lowercase letters in string to uppercase.

lower() string_name.lower()

The method lower() converts uppercase letters in string to lowercase.

count() string_name.count(substring [, start [, end]])

The method count(), returns the number of nonoverlapping occurrences of substring in the range [start, end].
Optional arguments start and end are interpreted as in slice notation.

>>> "2018".isdigit()

True

>>> fact.islower()

False
>>> "TSAR BOMBA".isupper()

True

>>> "columbus".islower()

True

.>>> warriors = "ancient gladiators were vegetarians"

>>> warriors.endswith("vegetarians")

True

>>> warriors.startswith("ancient")

True

>>> warriors.startswith("A")

False

>>> warriors.startswith("a")

True

>>> warriors.count("a")

>>> species = "charles darwin discovered galapagos tortoises"

>>> species.capitalize()

'Charles darwin discovered galapagos tortoises'

>>> warriors.count("a")

6. Write a note on indexing and slicing lists.

Indexing : As an ordered sequence of elements, each item in a list can be called individually, through indexing. The
expression inside the bracket is called the index. Lists use square brackets [ ] to access individual items, with the first
item at index 0, the second item at index 1 and so on. The index provided within the square brackets indicates the
value being accessed. The syntax for accessing an item in a list is, list_name[index] where index should always be an
integer value and indicates the item to be selected. For the list superstore, the index breakdown is shown below.

1. >>> superstore = ["metro", "tesco", "walmart", "kmart", "carrefour"]

2. >>> superstore[0]
'metro'

3. >>> superstore[1]

'tesco'

4. >>> superstore[2]

'walmart

Slicing of lists : is allowed in Python wherein a part of the list can be extracted by specifying index range along
with the colon (:) operator which itself is a list. The syntax for list slicing is,

where both start and stop are integer values (positive or negative values). List slicing returns a part of the list from
the start index value to stop index value which includes the start index value but excludes the stop index value. Step
specifies the increment value to slice by and it is optional. For the list fruits, the positive and negative index
breakdown is shown below.

1. >>> fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]

2. >>> fruits[1:3]

['pineapple', 'blueberries']

3. >>> fruits[:3]

['grapefruit', 'pineapple', 'blueberries']

4. >>> fruits[2:]

['blueberries', 'mango', 'banana']

5. >>> fruits[1:4:2]

['pineapple', 'mango']

7. Explain any five list methods with syntax.


>>> cities = ["oslo", "delhi", "washington", "london", "seattle", "paris", "washington"]

>>> cities.count('seattle')

>>> cities.index('washington')

>>> cities.reverse()

cities ['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo']

>>> cities.append('brussels')

cities ['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo', 'brussels']

>>> cities.sort()

['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'washington']

>>> cities.pop()

'washington'

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

def display_stack_items():
print("Current stack items are: ")
for item in stack:
print(item)
def push_item_to_stack(item):
print(f"Push an item to stack {item}")
if len(stack) < stack_size:
stack.append(item)
else:
print("Stack is full!")
def pop_item_from_stack():
if len(stack) > 0:
print(f"Pop an item from stack {stack.pop()}")
else:
print("Stack is empty.")
stack = []
stack_size = 3
push_item_to_stack(1)
push_item_to_stack(2)
push_item_to_stack(3)
display_stack_items()
push_item_to_stack(4)
pop_item_from_stack()
display_stack_items()
pop_item_from_stack()
pop_item_from_stack()
pop_item_from_stack()

9. Write a Python code to implement queue operations using lists

from collections import deque


def queue_operations():
queue = deque(["Eric", "John", "Michael"])
print(f"Queue items are {queue}")
print("Adding few items to Queue")
queue.append("Terry")
queue.append("Graham")
print(f"Queue items are {queue}")
print(f"Removed item from Queue is {queue.popleft()}")
print(f"Removed item from Queue is {queue.popleft()}")
print(f"Queue items are {queue}")
queue_operations()

Output:

Queue items are deque(['Eric', 'John', 'Michael'])


Adding few items to Queue
Queue items are deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])
Removed item from Queue is Eric
Removed item from Queue is John
Queue items are deque(['Michael', 'Terry', 'Graham'])

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. You can traverse through the items of nested lists using the for loop.

Each list inside another list is separated by a comma. For example,

You can access an item inside a list that is itself inside another list by chaining two sets of square brackets together.
For example, in the above list variable asia you have three lists ➀ which represent a 3 × 3 matrix. If you want to
display the items of the first list then specify the list variable followed by the index of the list which you need to
access within the brackets, like asia[0] ➁. If you want to access "Japan" item inside the list then you need to specify
the index of the list within the list and followed by the index of the item in the list, like asia[0][1] ➂. You can even
modify the contents of the list within the list. For example, to replace "Thailand" with "Philippines" use the code in
➃.

11. With example explain how to Access and Modify key:value Pairs in Dictionaries

The syntax for accessing the value for a key in the dictionary is,

dictionary_name[key]
eg: >>>dict1 = {'Name': 'Brinda', 'Id': 200, 'Salary': 9080.50}

>>>dict1['Name']

Brind

The syntax for modifying the value of an existing key or for adding a new key:value pair to a dictionary is,

dictionary_name[key] = value

eg: >>>dict1 = {'Name': 'Brinda', 'Id': 200, 'Salary': 9080.50}

>>>dict1['Name']=”Aravind”

>>>dict1

>>>={'Name': 'Aravind', 'Id': 200, 'Salary': 9080.50}

12.Explain any five dictionary methods with syntax.


Eg:

>>>box_office_billion={"avatar":2009,"titanic":1997,"starwars":2015,"harrypotter":2011,"avengers":2012}

>>>box_office_billion.keys()

dict_keys(['avatar', 'titanic', 'starwars', 'harrypotter', 'avengers'])

>>> box_office_billion.values()

dict_values([2009, 1997, 2015, 2011, 2012])

>>> box_office_billion.items()

dict_items([('avatar', 2009), ('titanic', 1997), ('starwars', 2015), ('harrypotter', 2011), ('avengers', 2012)])

>>> box_office_billion.update({"frozen":2013})

>>> box_office_billion

{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012, 'frozen': 2013}

>>> box_office_billion.pop("avatar")

2009

>>> box_office_billion.popitem()

('ironman', 2013)

>>> box_office_billion.clear()

{}

13.Write a Python Program to Dynamically Build dictionary using User Input as a List

def main():
print("Method 1: Building Dictionaries")
build_dictionary = {}
for i in range(0, 2):
dic_key = input("Enter key ")
dic_val = input("Enter val ")
build_dictionary.update({dic_key: dic_val})
print(f"Dictionary is {build_dictionary}")
print("Method 2: Building Dictionaries")
build_dictionary = {}
for i in range(0, 2):
dic_key = input("Enter key ")
dic_val = input("Enter val ")
build_dictionary[dic_key] = dic_val
print(f"Dictionary is {build_dictionary}")
main()

14.Explain with example how to traverse dictionary using key:value pair

A for loop can be used to iterate over keys or values or key:value pairs in dictionaries. If you iterate over a
dictionary using a for loop, then, by default, you will iterate over the keys. If you want to iterate over the values, use
values() method and for iterating over the key:value pairs, specify the dictionary’s items() method explicitly. The
dict_keys, dict_values, and dict_items data types returned by dictionary methods can be used in for loops to iterate
over the keys or values or key:value pairs

currency = {"India": "Rupee", "USA": "Dollar", "Russia": "Ruble", "Japan": "Yen", "Germany": "Euro"}

def main():
print("List of Countries")
for key in currency.keys():
print(key)
print("List of Currencies in different Countries")
for value in currency.values():
print(value)
for key, value in currency.items():
print(f"'{key}' has a currency of type '{value}'")
main()
15.Write a note on indexing and slicing tuples

Each item in a tuple can be called individually through indexing. The expression inside the bracket is called the index.
Square brackets [ ] are used by tuples to access individual items, with the first item at index 0, the second item at
index 1 and so on. The index provided within the square brackets indicates the value being accessed. The syntax for
accessing an item in a tuple is,

tuple_name[index]

where index should always be an integer value and indicates the item to be selected. For the tuple holy_places, the
index breakdown is shown below

For example,

1. >>> holy_places = ("jerusalem", "kashivishwanath", "harmandirsahib", "bethlehem", "mahabodhi")

2. >>> holy_places

('jerusalem', 'kashivishwanath', 'harmandirsahib', 'bethlehem', 'mahabodhi')

3. >>> holy_places[0]

'jerusalem'

4. >>> holy_places[1]

'kashivishwanath'

5. >>> holy_places[2]

'harmandirsahib

For the same tuple holy_places, the negative index breakdown is shown below.

For example, 1. >>> holy_places[-2] 'bethlehem


Slicing of tuples is allowed in Python wherein a part of the tuple can be extracted by specifying an index
range along with the colon (:) operator, which itself results as tuple type. The syntax for tuple slicing is

where both start and stop are integer values (positive or negative values). Tuple slicing returns a part of the tuple
from the start index value to stop index value, which includes the start index value but excludes the stop index value.
The step specifies the increment value to slice by and it is optional. For the tuple colors, the positive and negative
index breakdown is shown below.

For example,

1. >>> colors = ("v", "i", "b", "g", "y", "o", "r")

2. >>> colors

('v', 'i', 'b', 'g', 'y', 'o', 'r')

3. >>> colors[1:4]

('i', 'b', 'g')

4. >>> colors[:5]

('v', 'i', 'b', 'g', 'y')

5. >>> colors[3:]

('g', 'y', 'o', 'r')

6. >>> colors[:]

('v', 'i', 'b', 'g', 'y', 'o', 'r')

16. Write a Python program to populate tuple with user input data.

tuple_items = ()
total_items = int(input("Enter the total number of items: "))
for i in range(total_items):
user_input = int(input("Enter a number: "))
tuple_items += (user_input,)
print(f"Items added to tuple are {tuple_items}")
list_items = []
total_items = int(input("Enter the total number of items: "))
for i in range(total_items):
item = input("Enter an item to add: ")
list_items.append(item)
items_of_tuple = tuple(list_items)
print(f"Tuple items are {items_of_tuple}")

17.Explain any Five set methods.

1. >>> european_flowers = {"sunflowers", "roses", "lavender", "tulips", "goldcrest"}


2. >>> american_flowers = {"roses", "tulips", "lilies", "daisies"}

3. >>> american_flowers.add("orchids")

4. >>> american_flowers.difference(european_flowers) {'lilies', 'orchids', 'daisies'}

5. >>> american_flowers.intersection(european_flowers) {'roses', 'tulips'}

6. >>> american_flowers.isdisjoint(european_flowers) False

7. >>> american_flowers.issuperset(european_flowers) False

8. >>> american_flowers.issubset(european_flowers) False

9. >>> american_flowers.symmetric_difference(european_flowers) {'lilies', 'orchids', 'daisies', 'goldcrest', 'sunflowers',


'lavender'}

10. >>> american_flowers.union(european_flowers) {'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses',


'goldcrest', 'daisies'}

11. >>> american_flowers.update(european_flowers)

12. >>> american_flowers {'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses', 'goldcrest', 'daisies'}

13. >>> american_flowers.discard("roses")

14. >>> american_flowers {'lilies', 'tulips', 'orchids', 'daisies'}

>>> european_flowers.pop()

'tulips'

1>>> american_flowers.clear()

1>>> american_flowers

set()

You might also like