L6 - L7List - Set - Tuple - Dictionaries - Type Conversion
L6 - L7List - Set - Tuple - Dictionaries - Type Conversion
List
List is a data type of Python used to store multiple values of different types of data at a time. List are
represented with [].
A list can be created by putting comma separated values between square brackets [].
The following program shows creation of two lists namely list1 and list2 :
list1 = [1, 2, "one", "hi"]
list2 = [4, 5, "hello"]
Index range between 0 to n-1, where n is the number of values in the list
Python allows negative indexing for lists. The index of -1 refers to the last value of the list, -2 refers to
the second last value of the list and so on.
Printing Lists
The lists can be printed using the in-built function print() as shown below.
Accessing Values in Lists: A value at a particular index in a list is accessed using listname[index]
Slicing lists: Slicing is used to access a subset of a list. For a list l = [1, 4, 5, 7, 4, 15], a subset of list
from 2nd index to 4th index is obtained by l[2:4] which is equal to [5,7]. Slicing can be understood
using the following examples:
Every element in the set should be unique (no duplicates) and must be immutable
(which cannot be changed). But the set itself is mutable. We can add or remove
items / elements from it.
Note : Mutable data types like list, set and dictionary cannot become elements of a
set.
The set itself is mutable i.e. we can add or remove elements from the set.
A. 1,2,3 and 4
B. 2,3 and 4
C. 3 and 4
D. Only 3
Which of the following options are correct?
1. A set is an ordered collection of unique items.
2. myset = { }, creates an empty set.
3. A set is represented using curly braces { } .
4. Set allows duplicate elements.
5. Set is a immutable data type.
6. The elements of a set are mutable.
A. 1,2,3 and 4
B. 2,3 and 4
C. 3 and 4
D. Only 3
Sets
• Sets are used to store multiple values in a single variable.
• It is one of the four built-in data types of Python used to store collection of data. The
other 3 are lists, tuples and dictionaries.
• Set items are unchangeable (immutable) but we can add and remove the items from
the set.
O/P: {“a”,”b”,”c”,True,2}
Length of a set
• len() function is used to calculate the length of a set.
• print(len(thisset))
Access items of a set
• You cannot access items in the set by referring to an index or a key.
• You can use for loop for the same.
a = {“apple”, “banana”, “cherry”, 1, 2, 3}
for x in a:
print(x)
Check a specific value in the set
• print(“banana” in a)
• O/P: True or False
Change items
• Once an item is created in the set you cannot change it.
• We can add/remove the items.
Adding a new item
• add() method is used.
a = {1,2,3,4}
a.add(5)
print(a)
Add sets
a = {1,2,3,4}
b = {4,5,3,6}
a.update(b)
print(a)
O/P: {1,2,3,4,5,6}
Add any other iterable
• The object in the update() method does not have to be a set, it can be
any other data type also like a list, tuple or a dictionary.
a = {“apple”,”banana”,”cherry”}
mylist = [“kiwi”,”orange”]
a.update(mylist)
Remove item
• The items from a set can be removed by remove()/ discard()/ pop()
methods.
• 1) remove(): If item does not exist, remove() will raise the error.
a = {1,2,3,4}
a.remove(1)
print(a)
Remove an item
• 2) discard(): if item does not exist, then discard() will not raise the
error.
a.discard(2)
s1.update(s2)
print(s1)
Keep only duplicates
• Intersection_update(): This method keep only those items which are
present in both sets.
x.intersection_update(y)
print(x)
Keep all, but not duplicates
• x.symmetric_difference_update(y)
Tuples
Once a tuple is defined, we cannot add elements in it or remove elements from it.
A tuple can be converted into a list so that elements can be modified and converted back to a tuple. Conversion
of a tuple into a list and a list into a tuple is discussed in the later sessions.
• Tuple items are indexed, the first item has index [0] and so on.
Tuple
• Tuple items are ordered, unchangeable and allow duplicate values.
• Ordered: Ordered means it has a defined order and that order will not
change.
• Allow duplicates: Since tuples are indexed, so they can have items with the
same values.
Tuple length
• len() function is used to find out the number of items in a tuple.
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple item-data types
• Tuple items can be of any data type:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
tuple4 = ("abc", 34, True, 40, "male")
tuple() constructor
• It is also possible to use the tuple() constructor to make a tuple.
print(thistuple[:4])
Question
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[2:])
Question
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[-4:-1])
Check if the item exist
• To determine if a specified item is present in a tuple use the in
keyword.
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Update tuples
• Tuples are unchangeable, meaning that you cannot change, add, or
remove items once the tuple is created.
Update tuples - Solution
• Once a tuple is created, you cannot change its values. Tuples are
unchangeable, or immutable as it also is called.
• But there is a workaround. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.
Update tuples - Solution
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Add items
• Since tuples are immutable, they do not have a built-in append()
method, but there are other ways to add items to a tuple.
Add items
1) Convert into a list: Just like the workaround for changing a tuple,
you can convert it into a list, add your item(s), and convert it back
into a tuple.
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Add items
2) Add tuple to a tuple. You are allowed to add tuples to tuples, so if
you want to add one item, (or many), create a new tuple with the
item(s), and add it to the existing tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Remove items
• You cannot remove items in a tuple. Tuples are unchangeable, so you
cannot remove items from it.
print(mytuple)
Tuple methods
• count(): Returns the number of times a specified value occurs in a
tuple
Dictionaries
Dictionary is an unordered collection of key and value pairs.
Immutable data types like number, string, tuple etc. are used for the key and any data type is used for the
value.
Dictionaries are optimized to retrieve values when the keys are known.
Dictionaries are represented using key-value pairs separated by commas inside curly braces {}. The key-
value pairs are represented as key : value. For example, daily temperatures in major cities are mapped into
a dictionary as { "Hyderabad" : 27 , "Chennai" : 32 , "Mumbai" : 40 }.
Creating a dictionary:
A dictionary can be created in two ways.
• Using the built-in dict() function.
• Assigning elements directly.
Which of the following are the correct options?
1.Dictionary is a Python data type to store multiple values.
2.We use parenthesis () to define a dictionary.
3.In dictionary we represent an element in the {key-value} format.
4.Keys of the dictionary cannot be changed.
5.dictionary() function is used to create an empty dictionary.
A. 1,2,3
B. 1,4
C. 1,4,5
D. 1,3,5
Which of the following are the correct options?
1.Dictionary is a Python data type to store multiple values.
2.We use parenthesis () to define a dictionary.
3.In dictionary we represent an element in the {key-value} format.
4.Keys of the dictionary cannot be changed.
5.dictionary() function is used to create an empty dictionary.
A. 1,2,3
B. 1,4
C. 1,4,5
D. 1,3,5
Accessing elements of Dictionary
We cannot use numerical index (as in lists, tuples and strings) to access the items/elements of the dictionaries as dictionaries are unordered.
(Imagine all the items of a dictionary are put in a bag and jumbled, so there is no order and we cannot retrieve the items using a sequential
index.)
More points in relation to Dictionary
Dictionaries
• 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.
• Dictionaries are written with curly brackets, and have keys and values.
Creation of a dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
print(len(thisdict))
Dictionary Items - Data Types
• The values in dictionary items can be of any data type: String, int,
boolean, and list data types.
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
type()
• From Python's perspective, dictionaries are defined as objects with
the data type 'dict':
The dict() Constructor
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Access Dictionary items
• There is also a method called get() that will give you the same result.
x = thisdict.get("model")
Get keys
• The keys() method will return a list of all the keys in the dictionary.
x = thisdict.keys()
Get values
• The values() method will return a list of all the values in the
dictionary.
x = thisdict.values()
Make a change in the original dictionary, and
see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
car["year"] = 2020
x = car.keys()
car["color"] = "white"
x = thisdict.items()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Output
Yes, 'model' is one of the keys in the thisdict dictionary
Change values
• You can change the value of a specific item by referring to its key
name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Remove items
• There are several methods to remove the dictionary items
• These are pop(), popitem() and del
Pop()
• This method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)