Unit Ii
Unit Ii
2. >>> fruits[1:3]
['pineapple', 'blueberries']
3. >>> fruits[:3]
4. >>> fruits[2:]
Let's take a dictionary by the name 'dict' that contains employee details:
>>>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
>>>dict1['Name']=”Aravind”
>>>dict1
Ans:
for k, v in colors.items():
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.
Eg:
Tup2=tuple()
18.What is the output of print (tuple[1:3]) if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
Ans:
my_list = list(my_tuple)
print(my_list)
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'
>>> 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,
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.
2. >>> ":".join(date_of_birth)
'17:09:1950'
Concatenation:
1. >>> string_1 = "face"
4. >>> concatenated_string
'facebook'
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:
'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.
True
The capitalize() method returns a copy of the string with its first character capitalized and the rest lowercased.
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
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()
lower() string_name.lower()
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.endswith("vegetarians")
True
>>> warriors.startswith("ancient")
True
>>> warriors.startswith("A")
False
>>> warriors.startswith("a")
True
>>> warriors.count("a")
>>> species.capitalize()
>>> warriors.count("a")
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.
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.
2. >>> fruits[1:3]
['pineapple', 'blueberries']
3. >>> fruits[:3]
4. >>> fruits[2:]
5. >>> fruits[1:4:2]
['pineapple', 'mango']
>>> cities.count('seattle')
>>> cities.index('washington')
>>> cities.reverse()
>>> cities.append('brussels')
>>> cities.sort()
>>> cities.pop()
'washington'
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()
Output:
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.
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
>>>dict1['Name']=”Aravind”
>>>dict1
>>>box_office_billion={"avatar":2009,"titanic":1997,"starwars":2015,"harrypotter":2011,"avengers":2012}
>>>box_office_billion.keys()
>>> box_office_billion.values()
>>> 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()
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,
2. >>> holy_places
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.
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,
2. >>> colors
3. >>> colors[1:4]
4. >>> colors[:5]
5. >>> colors[3:]
6. >>> colors[:]
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}")
3. >>> american_flowers.add("orchids")
12. >>> american_flowers {'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses', 'goldcrest', 'daisies'}
>>> european_flowers.pop()
'tulips'
1>>> american_flowers.clear()
1>>> american_flowers
set()