0% found this document useful (0 votes)
3 views63 pages

Python Chapter 4,5

hh

Uploaded by

aniissiciid
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)
3 views63 pages

Python Chapter 4,5

hh

Uploaded by

aniissiciid
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

Python

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

1.L1 = ["John", 102, "USA"]

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. The lists are ordered.

2. The element of the list can access by index.

3. The lists are the mutable type.

4. The lists are mutable types.

5. A list can store the number of various elements.


 Let's check the first statement that lists are the ordered.

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

1.a = [1, 2,“Abdi", 4.50,"Ricky",5, 6]

2.b = [1, 2,“Abdi", 4.50,"Ricky",5, 6]

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)

•The start denotes the starting index position of the list.

•The stop denotes the last index position of the list.

•The step is used to skip the nth element within a start:stop


Consider the following example:
[Link] = [1,2,3,4,5,6,7]

[Link](list[0])

[Link](list[1])

[Link](list[2])

[Link](list[3])

6.# Slicing the elements

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

Python also provides append() and insert() 6.# Adding multiple-element

methods, which can be used to add values to [Link][1:3] = [89, 78]


the list. [Link](list)

Consider the following example to update 9.# It will add value at the end of the list

the values inside the list. [Link][-1] = 25

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

Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.


Python List Operations
Operator Description Example
Repetition The repetition operator enables the list L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
elements to be repeated multiple times.

Concatenation It concatenates the list mentioned on either l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]


side of the 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.

Length It is used to get the length of the list len(l1) = 4


Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which can be
iterated as follows.

[Link] = [“warfa", “ahmed", “jamici", “idil"]

[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]("printing original list: ");

[Link] i in list:

4. print(i,end=" ")

[Link](2)

[Link]("\nprinting the list after the removal of first element...")

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

2 len(list) It is used to calculate the length of L1 = [1,2,3,4,5,6,7,8] print(len(L1))


the list. 8

3 max(list) It returns the maximum element of L1 = [12,34,26,48,72]


the list. print(max(L1)) 72

4 min(list) It returns the minimum element of L1 = [12,34,26,48,72]


the list. print(min(L1)) 12

5 list(seq) It converts any sequence to the list. str = "Johnson" s = list(str)


print(type(s)) <class list>
Example:2- Write a program to find the sum
of the element in the list.
1.list1 = [3,4,5,9,10,12,24]

[Link] = 0

[Link] i in list1:

4. sum = sum+i

[Link]("The sum is:",sum)


Example: 3- Write the program to find the
lists consist of at least one common element.
1.list1 = [1,2,3,4,5,6]

2.list2 = [7,8,9,2,10]

[Link] x in list1:

4. for y in list2:

5. if x == y:

6. print("The common element is:",x)


List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value

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

insert() Adds an element at the specified position


pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since the value of the items
stored in the list can be changed, whereas the tuple is immutable, and the value of the items stored in the tuple cannot be
changed.
Creating a tuple

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

1.T1 = (101, "Peter", 22)

2.T2 = ("Apple", "Banana", "Orange")

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.

Tuples are written with round brackets.


Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.

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

3.#Creating a tuple with single element

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:

1.tuple1 = (10, 20, 30, 40, 50, 60)

[Link](tuple1)

[Link] i in tuple1:

4. print(i)

5.
Tuple Items - Data Types
Tuple items can be of any data type:

Example: String, int and Boolean data types:

tuple1 = ("apple", "banana", "cherry")

tuple2 = (1, 5, 7, 9, 3)

tuple3 = (True, False, False)

A tuple can contain different data types:

Example:A tuple with strings, integers and Boolean values:

tuple1 = ("abc", 34, True, 40, "male")


Cont..
type():From Python's perspective, tuples are defined as objects with the data type 'tuple’:

 Python Collections (Arrays)

There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate members.

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate


members.
Dictionary is a collection which is ordered** and changeable. No duplicate
members.
Python - Access Tuple Items

Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets:

Example: Print the second item in the tuple:

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


print(thistuple[1])
Negative Indexing

Example: Print the last item of the tuple:

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


print(thistuple[-1])
Range of Indexes

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

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:5])
Check if Item Exists

To determine if a specified item is present in a tuple use the in keyword:

Example

Check if "apple" is present in the tuple:

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


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Python - Loop Tuples

Loop Through a Tuple

You can loop through the tuple items by using a for loop.

Example: Iterate through the items and print the values:

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


for x in thistuple:
print(x)
Loop Through the Index Numbers

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

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


for i in range(len(thistuple)):
print(thistuple[i])
List vs. Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().

2 The List is mutable. The tuple is immutable.


3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality than a tuple. The tuple provides less functionality than the list.

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] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

[Link](Days)

[Link](type(Days))

[Link]("looping through the set elements ... ")

[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]("looping through the set elements ... ")

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

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
Get the Length of a Set

To determine how many items a set has, use the len() function.

Example

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))
Set Items - Data Types

Set items can be of any data type:

 Example
String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
A set can contain different data types:

Example
A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}


Python - Access Set Items

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

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Example

Check if "banana" is present in the set:


thisset = {"apple", "banana", "cherry"}

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.

To add one item to a set use the add() method.

Example
Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}

[Link]("orange")

print(thisset)
Add Sets using update

To add items from another set into the current set, use the update() method.

Example

Add elements from tropical into thisset:


thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

[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

Add elements of a list to at set:


thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

[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

Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
Python - Join Sets

Join Two Sets

There are several ways to join two or more sets in Python.

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

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

set3 = [Link](set2)
print(set3)
Example

The update() method inserts the items in set2 into set1:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

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

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

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

Create and print a dictionary:

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

Get the value of the "model" key:

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

print(x) #before the change

car["color"] = "white"

print(x) #after the change


Get Values

The values() method will return a list of all the values in the dictionary.

Example

Get a list of the values:

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

print(x) #before the change

car["year"] = 2020

print(x) #after the change


Get Items

The items() method will return each item in a dictionary, as tuples in a list.

Example

Get a list of the key:value pairs

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

To determine if a specified key is present in a dictionary use the in keyword:

Example

Check if "model" is present in the dictionary:

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

Change the "year" to 2018:

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.

The argument must be a dictionary, or an iterable object with key:value pairs.

Example

Update the "year" of the car by using the update() method:

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

There are several methods to remove items from a dictionary:

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

Loop Through a Dictionary

You can loop through a dictionary by using a for loop.

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

Print all key names in the dictionary, one by one:

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)

You might also like