0% found this document useful (0 votes)
21 views95 pages

L6 - L7List - Set - Tuple - Dictionaries - Type Conversion

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

L6 - L7List - Set - Tuple - Dictionaries - Type Conversion

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

List, Set, Tuple ,Dictionaries, Data 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"]

 Values stored in the list are accessed using an index.

 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:

Concatenating lists: We can concatenate two lists using (+) operator.


Repeating lists: We can print a list multiple times using (*) operator as shown below:
Sample Question:
Solution:
list1 = [1.0, 2.3, "hello"]
list2 = ["hi", 8.3, 9.6, "how"]
print("List1 Elements are:",list1)
print("List2 Elements are:",list2)
print("List after Concatenation:",list1+list2)
Sets
A set is a mutable data type that contains an unordered collection of items.

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

The main uses of sets are:


• Performing mathematical operations such as intersection, union, difference, and
symmetric difference
• A set is represented with { }.
Creation of sets
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by
using the built-in function set().
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
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.

• A set is a collection whose elements are unordered, unchangeable and unindexed.

• Set items are unchangeable (immutable) but we can add and remove the items from
the set.

• Sets ate mutable objects.


Sets
• A set is unordered, unchangeable and contains no duplicates.
• Unordered: The items in the set do not have a defined order. Set items can
appear in a different order every time you use them. So, it cannot be referred
by any index or key.

• Unchangeable: Set items are unchangeable means we cannot change the


items after a set has been created.

• No duplicates: Duplicates will be ignored.


Duplicates not allowed
• The values True and 1 are considered to be the same values in the set.

a = {“a”, ”b”, ”c”, True, 1, 2}


print(a)

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)

• 3) pop(): pop() method removes a random element.


x = a.pop()
print(x)
Remove the set
• Clear(): This method clears the set.
a.clear()

• Delete(): This method deletes the set completely


del a
Join two sets
• This can be done using union() and update() methods.
• Union(): Returns a new set containing all items from both sets.

a={‘a’, ’b’, ’c’}


b={1, 2, 3}
c=a.union(b)
print(c)
Join two sets
• Update(): This method inserts the items of set2 into set1.

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

 A tuple is a data type similar to list.


 The major differences between the two are: Lists are enclosed in square brackets [] and their elements
and size can be changed (mutable), while tuples are enclosed in parentheses () and their elements
cannot be changed (immutable).
 Tuples can be thought of as read-only lists.

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

 A tuple is represented using parenthesis ( ).


Which of the following options are correct?
1.Tuples are used to store similar type of data.
2.tuple1 = (1.0) is correct way to create a tuple with single element.
3.tuples are immutable.
4.Lists are immutable.
5.Converting a tuple into a list and list into tuple is possible.
6.Lists are faster than tuples.
A. 1,2,3
B. 2,3
C. 3,5
D. 2,3,4
Which of the following options are correct?
1.Tuples are used to store similar type of data.
2.tuple1 = (1.0) is correct way to create a tuple with single element.
3.tuples are immutable.
4.Lists are immutable.
5.Converting a tuple into a list and list into tuple is possible.
6.Lists are faster than tuples.
A. 1,2,3
B. 2,3
C. 3,5
D. 2,3,4
Tuples
• Tuples are used to store multiple items in a single variable.

• Tuple is one of 4 built-in data types in Python used to store collections


of data, the other 3 are List, Set, and Dictionary, all with different
qualities and usage.

• Tuples are written with round brackets.


Creation of a tuple
thistuple = (“apple”, ”banana”, ”cherry”)
print(thistuple)
Tuple

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

• Unchangeable: Tuples are unchangeable.

• 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", "banana", "cherry")


print(len(thistuple))
Creation of tuple with one item
• To create a tuple with only one item, you have to add a comma after
the item, otherwise Python will not recognize it as 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.

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(thistuple)
Access tuple items
• You can access tuple items by referring to the index number, inside
square brackets:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])
Access tuple items
• You can specify a range of indexes by specifying where to start and
where to end the range.
• When specifying a range, the return value will be a new tuple with the
specified items.

Q: Return the third, fourth, and fifth item:


thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[2:5])
Question
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")

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.

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
Remove tuple
• Or we can delete the tuple completely using del

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
Join tuples
• To join two or more tuples you can use the + operator:

tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)
Multiply tuples
• If you want to multiply the content of a tuple a given number of
times, you can use the * operator.

fruits = ("apple", "banana", "cherry")


mytuple = fruits * 2

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.

General usage of dictionaries is to store key-value pairs like :


• Employees and their wages
• Countries and their capitals
• Commodities and their prices
 In a dictionary, the keys should be unique, but the values can change. For example, the price of a
commodity may change over time, but its name will not change.

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

O/P: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}


Dictionary items
• Dictionary items are ordered, changeable, and does not allow
duplicates.

• Dictionary items are presented in key:value pairs, and can be referred


to by using the key name.
Printing the dictionary items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Changeable
• Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates not allowed
• Dictionaries cannot have two items with the same key.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary length
• To determine how many items a dictionary has, use the len() function.

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

• It is also possible to use the dict() constructor to make a dictionary.

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)
Access Dictionary items
• You can access the items of a dictionary by referring to its key name,
inside square brackets:

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

print(x) #before the change

car["year"] = 2020

print(x) #after the change


Add a new item to the original dictionary, and
see that the keys list gets updated as well:
• car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change


Output
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
Get items
• The items() method will return each item in a dictionary, as tuples in a
list.

x = thisdict.items()

O/P: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])


Check if key exist
• To determine if a specified key is present in a dictionary use the in
keyword.

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

O/P: {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}


Update dictionary
• The update() method will update the dictionary with the items from
the given argument.
• The argument must be a dictionary, or an iterable object with
key:value pairs.
Update the "year" of the car by using the
update() method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

O/P: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}


Adding items
• Adding an item to the dictionary is done by using a new index key and
assigning a value to it:

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)

O/P: {'brand': 'Ford', 'year': 1964}


Popitem()
• Popitem() method removes the last inserted item.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

O/P: {'brand': 'Ford', 'model': 'Mustang'}


del
• Del keyword removes the item with the specified key name:
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

• O/P: {'brand': 'Ford', 'year': 1964}


del
• Del also delete the dictionary completely.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.

You might also like