[go: up one dir, main page]

0% found this document useful (0 votes)
0 views25 pages

Slide 9

The document provides an overview of Python's built-in data types, including Lists, Tuples, Dictionaries, and Sets, explaining their creation, methods, and usage. It also introduces the Math module, detailing its functions and how to import it. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

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

Slide 9

The document provides an overview of Python's built-in data types, including Lists, Tuples, Dictionaries, and Sets, explaining their creation, methods, and usage. It also introduces the Math module, detailing its functions and how to import it. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

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

Python Practical-07

List
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to


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

Lists are created using square brackets.

2
Creating List
Using square brackets: my_list = [element1, element2,
...]
Empty lists: empty_list = []
Lists can hold different data types.

3
Accessing List Elements
Let’s create the following list named students:
students = [‘Ross’, ‘Rachel’, ‘Monica’, ‘Chandler’]

Indexing: Accessing elements by their position (0-based


index). In order to print Monica’s name:
print(students[2])
Negative indexing: Counting from the end. In order to type
Chandler’s name:
print(students[-1])
Slicing: Extracting sublists.
print(students[1:2])

4
List Methods
.append(): Adding an element to the end.
.insert(): Inserting an element at a specific position.
.remove(): Removing a specific element by value.
.pop(): Removing and returning an element by index.
.sort(): Sorting elements in ascending order.
.reverse(): Reversing the order of elements.
.index(): Finding the index of a specific element.
.count(): Counting occurrences of an element.

5
Practice: Finding Maximum Value in a List
numbers = [3, 5, 6, 7, 19, 1, 41, 5]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)

6
Nested Lists
Nested lists mean creating lists of lists. It can be used for matrix
representation. For example:

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

print(matrix [1] [2])

This will print the 3rd element of 2nd list which is 6.

7
Tuples
Tuples are used to store multiple items in a single variable.

A tuple is a collection which is ordered and unchangeable


(immutable).

Tuples are written with round brackets. For example:

students = (‘Ross’, ‘Rachel’, ‘Monica’, ‘Chandler’)

8
Tuple Methods
count(): Counting occurrences of a value.
index(): Finding the index of a value.

9
Dictionary
dicts or dictionaries is a data structure that allows you to
associate keys with values.
Where a list is a list of multiple values, a dict associates a key
with a value.
Dictionaries are written with curly brackets, and have keys and
values. For example:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

10
Dictionary Items
Dictionary items are ordered, changeable, and does not allow
duplicates.
The values in dictionary items can be of any data type.
Dictionary items are presented in key:value pairs, and can be
referred to by using the key name. For example, to print the
"brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

11
Dictionary (.get)
In order to avoid ‘KeyError’ feedback (typing a key that does not
exist in a dictionary), we can use “.get” to generate “None”
feedback. For example:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict.get(“frand“))

As there is no ‘frand’ key in the dictonary, the terminal will


generate the word ‘None’.

12
Using for loop in Dictionary
In order to print all the values in a dictionary, we can use the for
loop. For example:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for value in thisdict.values():
print(value)

13
Modifying and Adding in Dictionary
In dictionaries, values can be modified. For example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict[“year”] = 1974

In dictionaries, new key-value pairs can be added. For example:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict[“Origin”] = “USA”

14
Sets
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and do not
allow duplicate values.
A set can contain different data types.
Sets are written with curly brackets. For example:

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

print(thisset)

Here, “apple” will be printed only once since sets do not allow
duplicates.

15
The set() constructor
It is also possible to use the set() constructor to make a
set. For example:

thisset = set(("apple", "banana", "cherry"))


print(thisset)

16
Set Operations
.union(): Combining two sets (or using the | operator).
.intersection(): Finding common elements (or using the
& operator).
.difference(): Finding elements in one set but not the
other (or using the - operator).
.symmetric_difference(): Finding elements in either
set, but not both (or using the ^ operator).
.issubset(): Checking if a set is a subset of
another.
.issuperset(): Checking if a set is a superset of
another.

17
Set Operations Example
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
symmetric_difference_set=set1.symmetric_difference(set2)
subset_check = {4, 5}.issubset(set1)
superset_check = set1.issuperset({2, 3})

18
Module in Python
In Python, a module is a file containing Python code.
This code can include functions, classes, and variables
that can be used in other Python scripts.
Modules are used to organize and encapsulate code,
making it easier to manage and reuse.

19
Math Module
The math module in Python is a built-in module that
provides a set of mathematical functions and constants for
performing various mathematical operations.
It is part of the Python Standard Library, so you don't
need to install any additional packages to use it.
The math module includes functions for basic
mathematical operations (such as square roots and
exponentiation), trigonometric functions, logarithmic
functions, and more. Additionally, it provides
constants like π (pi) and e (Euler's number).

20
Math Module
To use the math module type the following command:
import math

To customize the ‘math’ command, type:


import math as m

To import a particular function of math command


(For example ‘sqrt’), type:
from math import sqrt

21
Common Functions
math.sqrt(x): Returns the square root of x.
math.pow(x, y): Returns x raised to the power of y.
math.exp(x): Returns the exponential of x (e^x).
math.log(x, base): Returns the natural logarithm of x (base e),
or the logarithm of x with the specified base.
math.pi: Represents the mathematical constant π (pi).
math.e: Represents the mathematical constant e (Euler's
number).
math.ceil(x): Returns the smallest integer greater than or equal
to x.
math.floor(x): Returns the largest integer less than or equal to
x.

22
Exercise

Take a radius from the user as input


and calculate the circumference of the
circle

23
Exercise

Calculate the hypotenuse of a right


triangle by taking values of two sides
of the triangle from the user.

24
That’s All
For Today!
25

You might also like