Python Chapter 4,5
Python Chapter 4,5
chapter
4
LIST, TUPLES, SETS,
DICTIONARY
Python List
A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we can
modify its element after it created. However, Python consists of six data-types that are capable to store the sequences, but
the most common and reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the list are separated with the
comma (,) and enclosed with the square brackets [].
A list can be define as below example
2.L2 = [1, 2, 3, 4, 5, 6]
[Link] we try to print the type of L1, L2, and L3 using type() function then it will come out to be a list.
[Link](type(L1))
[Link](type(L2))
Characteristics of Lists
The list has the following characteristics:
1.a = [1,2,“abdi",4.50,"Ricky",5,6]
2.b = [1,2,5,“abdi",4.50,"Ricky",6]
[Link](a ==b )
Cont..
Both lists have consisted of the same elements, but the second list changed the index position of
the 5th element that violates the order of lists. When compare both lists it returns the false.
Lists maintain the order of the element for the lifetime. That's why it is the ordered collection of
objects
3.a == b
List indexing and splitting
The indexing is processed in the same way as it happens with the strings. The elements of the
list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is
stored at the 0th index, the second element of the list is stored at the 1st
index, and so on.
We can get the sub-list of the list using the following
syntax.
list_varible(start:stop:step)
[Link](list[0])
[Link](list[1])
[Link](list[2])
[Link](list[3])
[Link](list[0:6])
8.# By default the index value is 0 so its starts from the 0th eleme
nt and go for index -1.
[Link](list[:])
[Link](list[2:5])
[Link](list[1:6:2])
Negative indexing
Unlike other languages, Python provides the flexibility to use the negative indexing also.
The negative indices are counted from the right. The last element (rightmost) of the list has
the index -1; its adjacent left element is present at the index -2 and so on until the left-most
elements are encountered.
Let's have a look at the following example where we will use
negative indexing to access the elements of the list.
[Link] = [1,2,3,4,5]
[Link](list[-1])
[Link](list[-3:])
[Link](list[:-1])
[Link](list[-3:-1])
Updating List values
[Link] = [1, 2, 3, 4, 5, 6]
Lists are the most versatile data structures [Link](list)
in Python since they are mutable, and their 3.# It will assign value to the value to the second index
values can be updated by using the slice and [Link][2] = 10
assignment operator. [Link](list)
Consider the following example to update 9.# It will add value at the end of the list
print(list)
11.
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were working
with the strings.
Let's see how the list responds to various operator
Membership It returns true if a particular item exists in a print(2 in l1) prints True.
particular list otherwise false.
Iteration The for loop is used to iterate over the list for i in l1: print(i)Output1 2 3 4
elements.
[Link] i in list:
3. # The i variable will iterate over the elements of the List and contains eac
h element in each iteration.
4. print(i)
Adding elements to the list
Python provides append() function which is used to add an element to the list. However, the
append() function can only add value to the end of the list.
Consider the following example in which, we are taking the elements of the list from the user
and printing the list on the console
Removing elements from the list
Python provides the remove() function which is used to remove the element from the list. Consider the following example to
understand this concept.
Example –
[Link] = [0,1,2,3,4]
[Link] i in list:
4. print(i,end=" ")
[Link](2)
[Link] i in list:
8. print(i,end=" ")
Python List Built-in functions
Python provides the following built-in functions, which can be used with the lists.
SN Function Description Example
1 cmp(list1, list2) It compares the elements of both This method is not used in the
the lists. Python 3 and the above versions.
[Link] = 0
[Link] i in list1:
4. sum = sum+i
2.list2 = [7,8,9,2,10]
[Link] x in list1:
4. for y in list2:
5. if x == y:
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
A tuple can be written as the collection of comma-separated (,) values enclosed with the small () brackets. The parentheses are
optional but it is good practice to use. A tuple can be defined as follows.
3.T3 = 10,20,30,40,50
4.
[Link](type(T1))
[Link](type(T2))
[Link](type(T3))
Tuple
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.
A tuple is a collection which is ordered and unchangeable.
Tuple items are indexed, the first item has index [0], the second item has index [1]
Ordered: When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.
Unchangeable: Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.
Allow Duplicates: Since tuples are indexed, they can have items with the same value:
An empty tuple can be created as
follows.
T4 = ()
Creating a tuple with single element is slightly different. We will need to put comma after the
element to declare the tuple.
1.tup1 = (“abdi")
[Link](type(tup1))
4.tup2 = (“abdi",)
[Link](type(tup2))
Example
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using
their specific index value.
Consider the following example of tuple:
[Link](tuple1)
[Link] i in tuple1:
4. print(i)
5.
Tuple Items - Data Types
Tuple items can be of any data type:
tuple2 = (1, 5, 7, 9, 3)
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate members.
You can access tuple items by referring to the index number, inside square brackets:
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.
Example
You can loop through the tuple items by using a for loop.
You can also loop through the tuple items by referring to their index number. Use the range() and len() functions
to create a suitable iterable.
Example :Print all items by referring to their index number:
5 The list is used in the scenario in which we need to store the The tuple is used in the cases where we need to store the read-only
simple collections with no constraints where the value of the collections i.e., the value of the items cannot be changed. It can be
items can be changed. used as the key inside the dictionary.
6 The lists are less memory efficient than a tuple. The tuples are more memory efficient because of its immutability.
Python Set
A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we
cannot directly access any element of the set by the index. However, we can print them all
together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python also
provides the set() method, which can be used to create the set by the passed sequence.
Example 1: Using curly braces
[Link](Days)
[Link](type(Days))
[Link] i in Days:
6. print(i)
Example 2: Using set() method
[Link] = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Satu
rday", "Sunday"])
[Link](Days)
[Link](type(Days))
[Link] i in Days:
6. print(i)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered: Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.
Unchangeable: Set items are unchangeable, meaning that we cannot change the items after the
set has been created.
Once a set is created, you cannot change its items, but you can remove items and add new items.
Duplicates Not Allowed: Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
print(thisset)
Get the Length of a Set
To determine how many items a set has, use the len() function.
Example
print(len(thisset))
Set Items - Data Types
Example
String, int and boolean data types:
Example
A set with strings, integers and boolean values:
Access Items: You cannot access items in a set by referring to an index or a key. But you can loop through the set items
using a for loop, or ask if a specified value is present in a set, by using the in keyword.
Example
Loop through the set, and print the values:
for x in thisset:
print(x)
Example
print("banana" in thisset)
Python - Add Set Items
Add Items
Once a set is created, you cannot change its items, but you can add new items.
Example
Add an item to a set, using the add() method:
[Link]("orange")
print(thisset)
Add Sets using update
To add items from another set into the current set, use the update() method.
Example
[Link](tropical)
print(thisset)
Add Any Iterable
The object in the update() method does not have to be a set, it can be any iterable object (tuples,
lists, dictionaries etc.).
Example
[Link](mylist)
print(thisset)
Python - Remove Set Items
Remove Item To remove an item in a set, use the remove() , or the Example
discard() method.
Remove "banana" by using the discard() method:
Example
thisset =
Remove "banana" by using the remove() method:
{"apple", "banana", "cherry"}
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
[Link]("banana")
print(thisset)
print(thisset)
Note: If the item to remove does not exist,
Note: If the item to remove does not exist, remove() will raise an
error. discard() will NOT raise an error.
Cont…
You can also use the pop() method to remove an
item, but this method will remove the last item. print(thisset)
Remember that sets are unordered, so you will not
Example
know what item that gets removed.
The del keyword will delete the set completely:
The return value of the pop() method is the
removed item. thisset =
{"apple", "banana", "cherry"}
Example
Remove the last item by using the pop() method: del thisset
thisset =
print(thisset)
{"apple", "banana", "cherry"}
x = [Link]()
print(x)
Loop Items
You can loop through the set items by using a for loop:
Example
for x in thisset:
print(x)
Python - Join Sets
You can use the union() method that returns a new set containing all items from both sets, or the update() method that
inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both sets:
set3 = [Link](set2)
print(set3)
Example
[Link](set2)
print(set1)
Note: Both union() and update() will exclude any duplicate items.
Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data
type in Python, which can simulate the real-life data arrangement where some specific value
exists for some particular key. It is the mutable data-structure. The dictionary is defined into
element Keys and values.
Dictionaries are used to store data values in key: value pairs.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
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.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Python - Access Dictionary Items
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
x = [Link]()
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary
will be reflected in the keys list.
Example
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 = [Link]()
car["color"] = "white"
The values() method will return a list of all the values in the dictionary.
Example
x = [Link]()
The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
Example
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 = [Link]()
car["year"] = 2020
The items() method will return each item in a dictionary, as tuples in a list.
Example
x = [Link]()
The returned list is a view of the items of the dictionary, meaning that any changes done to the
dictionary will be reflected in the items list.
Check if Key Exists
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Python - Change Dictionary Items
Change Values
You can change the value of a specific item by referring to its key name:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})
Python - Add Dictionary Items
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Python - Remove Dictionary Items
Removing Items
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
Python - Loop Dictionaries
When looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.
Example
for x in thisdict:
print(x)
Cont..
Example
Loop through both keys and values, by using the items() method:
for x, y in [Link]():
print(x, y)
Python - Copy Dictionaries
Copy a Dictionary
There are ways to make a copy, one way is to use the built-in Dictionary method copy()
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)