Professional Documents
Culture Documents
CSE114 Unit2
CSE114 Unit2
CSE114 Unit2
Lists and Nested List: Introduction, Accessing list, Operations, Working with lists,
Library Functions and Methods with Lists.
Tuple: Introduction, Accessing tuples, Operations, Working, Library Functions and
Methods with Tuples.
Dictionaries :Introduction, Accessing values in dictionaries, Working with dictionaries,
Library Functions
• The index must be an integer. We can't use float or other types, this will result
into TypeError.
TypeError: list indices must be integers or slices, not float
Example 1:
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])
Example:
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5]) # elements 3rd to 5th
print(my_list[:-5]) # elements beginning to 4th
print(my_list[5:]) # elements 6th to end
print(my_list[:]) # elements beginning to end
Q2)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Q3)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Q4)
s = "python rocks"
print(s[7:11] * 3)
By Ms. Preeti Kaushik
Q4)
# Python program to demonstrate accessing of element from list
Q 5)
thislist = ["apple","banana","cherry","orange","kiwi","melon","mango"]
print(thislist[-4:-1])
print(thislist[-1:-4]) # cannot print in reverse order. Prints []
By Ms. Preeti Kaushik
Loop through list
You can loop through the list items by using a for loop:
Example:
#program to print list element one by one
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Output:
apple
banana
cherry
Example:
odd = [2, 4, 6, 8]
odd[0] = 1 # change the 1st item
print(odd) # Output: [1, 4, 6, 8]
odd[1:4] = [3, 5, 7] # change 2nd to 4th items
print(odd) # Output: [1, 3, 5, 7]
Example:
odd = [1, 3, 5]
odd.append(7)
print(odd) # Output: [1, 3, 5, 7]
odd.extend([9, 11, 13])
print(odd) # Output: [1, 3, 5, 7, 9, 11, 13]
Example:
odd = [1, 3, 5]
print(odd + [9, 7, 5]) # Output: [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output: ["re", "re", "re"]
Example 1:
odd = [1, 9]
odd.insert(1,3)
print(odd) # Output: [1, 3, 9]
odd[2:2] = [5, 7]
print(odd) # Output: [1, 3, 5, 7, 9]
Example 2:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Output: ['apple', 'orange', 'banana', 'cherry']
By Ms. Preeti Kaushik
#Adding list one by one element using append
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Example:
my_list = ['p','r','o','b','l','e','m']
del my_list[2] # delete one item
print(my_list) # Output: ['p', 'r', 'b', 'l', 'e', 'm']
del my_list[1:5] # delete multiple items
print(my_list) # Output: ['p', 'm']
del my_list # delete entire list
print(my_list) # Error: List not defined
Example:
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm’]
output
['r', 'o', 'b', 'l', 'e', 'm']
Example:
my_list = ['p','r','o','b','l','e','m'] output
['p', 'r', 'o', 'b', 'l', 'e', 'm']
r
print(my_list) ['p', 'o', 'b', 'l', 'e', 'm']
print(my_list.pop(1)) m
print(my_list)
print(my_list.pop())
Example:
my_list = ['p','r','o','b','l','e','m']
print(my_list)
my_list.clear()
print(my_list)
output
['p', 'r', 'o', 'b', 'l', 'e', 'm']
[]
Example:
my_list = ['p','r','o','b','l','e','m']
my_list[2:3] = []
print(my_list)
my_list[2:5] = []
Print(my_list)
Output:
['p', 'r', 'b', 'l', 'e', 'm’]
['p', 'r', 'm’]
By Ms. Preeti Kaushik
Copy a list
• You cannot copy a list simply by typing list2 = list1, because: list2 will only be a
reference to list1, and changes made in list1 will automatically also be made in list2.
• We can copy using built in method a) copy() b) list()
• List length
use the len() function:
Example:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output
3
By Ms. Preeti Kaushik
Find output?
1) thislist = ["apple","banana","cherry"]
mylist=thislist
thislist[1]="abc"
print(thislist)
print(mylist)
2)
List = ['G','E','E','K','S','F','O','R','G','E','E','K','S']
print(List[::-1])
3)
thislist = ["apple","banana","cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
By Ms. Preeti Kaushik
Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
x=[23,-45,56,0]
for i in range(0,len(x)):
if x[i]>0:
x[i]=1
elif x[i]<0:
x[i]=-1
print(x)
• A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).
output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
Example:
my_tuple = 3, 4.6, "dog” #tuple packing
print(my_tuple) # Output: 3, 4.6, "dog"
a, b, c = my_tuple # tuple unpacking is also possible
print(a) #3
print(b) # 4.6
print(c) # dog
output
(3, 4.6, 'dog')
3
4.6
dog
By Ms. Preeti Kaushik
• Creating a tuple with one element is a bit tricky.
• Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in
fact, a tuple.
Example:
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>
output
<class 'str'>
<class 'tuple'>
<class 'tuple'>
By Ms. Preeti Kaushik
How to access tuple element?
• tuple elements can be accessed by
a) Index
b) Negative indexing
c) Using slice operator
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
output
p
t
s
4
Example:
my_tuple = ('p','e','r','m','i','t')
output
t
p
Example:
my_tuple = (4, 2, 3, [6, 5])
my_tuple[1] = 9
Output: TypeError: 'tuple' object does not support item assignment
• We can also repeat the elements in a tuple for a given number of times using the * operator.
Example:
# Concatenation
print((1, 2, 3) + (4, 5, 6)) output
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
# Repeat
print(("Repeat",) * 3)
Example:
my_tuple = ('p','r','o','g','r','a','m','i','z')
#can't delete items
# TypeError: 'tuple' object doesn't support item deletion
del my_tuple[3]
Output:
TypeError: 'tuple' object doesn't support item deletion
By Ms. Preeti Kaushik
Example 2:
my_tuple = ('p','r','o','g','r','a','m','i','z')
Example:
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
output
2
3
By Ms. Preeti Kaushik
Loop through tuple
• You can loop through the tuple items by using a for loop.
Example:
thistuple = ("apple", "banana", "cherry") Output:
apple
for x in thistuple:
banana
print(x) cherry
Example:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Output:
Yes, 'apple' is in the fruits tuple
1)
my_tuple = ('a','p','p','l','e',)
print('a' in my_tuple)
print('b' in my_tuple)
print('g' not in my_tuple)
Output: 3
example 1:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
By Ms. Preeti Kaushik
Dictionary creation
• Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
• An item has a key and the corresponding value expressed as a pair, key: value.
• While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
Example:
my_dict = {} # empty dictionary
output
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Example 1:
my_dict = {'name':'Jack','age': 26}
print(my_dict['name']) # Output: Jack
print(my_dict.get('age')) # Output: 26
Output:
Jack
26
By Ms. Preeti Kaushik
The difference while using get() is that it returns None instead of KeyError, if the key is not found.
Example 2:
my_dict = {'name':'Jack', 'age': 26}
print(my_dict.get('address’))
Output:
None
Example 3:
my_dict = {'name':'Jack', 'age': 26}
# Trying to access keys which doesn't exist throws error
print(my_dict['address’])
Output:
KeyError: 'address'
Example 1:
my_dict = {'name':'Jack', 'age': 26} output
{'name': 'Jack', 'age': 27}
my_dict['age'] = 27 # update value {'name': 'Jack', 'age': 27, 'address': 'Downtown'}
b) Popitem(): used to remove and return an arbitrary item (key, value) from
the dictionary.
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
Output:
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9} By Ms. Preeti Kaushik
Example 2:
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares) # Output: {}
Example 3:
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
del squares # delete the dictionary itself Output
NameError: name 'squares' is not defined
# Throws Error
print(squares)
By Ms. Preeti Kaushik
Copy a dictionary
• You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1
will automatically also be made in dict2.
Example :
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
print(2 not in squares) Output:
True
# membership tests for key only not value True
False
print(49 in squares) # Output: False
Output:
1
9
25
49
81
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)
Output:
brand Ford
model Mustang
year 1964
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict.keys())
print(thisdict.values())
print(thisdict.items())
Output:
dict_keys(['brand', 'model', 'year'])
dict_values(['Ford', 'Mustang', 1964])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
2) Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.
For example:
dict = {['Name']:'Zara','Age': 7}
print("dict['Name']: ", dict['Name’])
Output:
TypeError: unhashable type: 'list'
By Ms. Preeti Kaushik
cmp() function
• cmp() is an in-built function in Python, it is used to compare two objects and
returns value according to the given values. it returns negative, zero or
positive value based on the given input.
Syntax: cmp(obj1, obj2)
• Here, cmp() will return negative(1) if obj1<obj2, zero(0) if obj1=obj2,
positive (1) if obj1>obj2.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found,
pop(key[,d])
raises KeyError.
popitem() Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys.