0% found this document useful (0 votes)
15 views

Ceng240 Week 3

This lecture introduces Python programming concepts including numbers, Boolean values, and various container data types such as strings, lists, tuples, dictionaries, and sets. It also covers the mutability of data types and the aliasing problem, along with basic operations and logical operators. The session aims to prepare students for practical labs starting next week.

Uploaded by

eagac2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Ceng240 Week 3

This lecture introduces Python programming concepts including numbers, Boolean values, and various container data types such as strings, lists, tuples, dictionaries, and sets. It also covers the mutability of data types and the aliasing problem, along with basic operations and logical operators. The session aims to prepare students for practical labs starting next week.

Uploaded by

eagac2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

Programming with Python for Engineers

Lecture-3
Lecture : Week-3
Subject : Introduction to Python
- Numbers and Boolean values,
- Container data (str, tuple, list, dict, set);
- Mutable - immutable data;
- Aliasing problem

Lecturer: Hüseyin SAYIN


E-Mail : hsayin@metu.edu.tr
Coordinating Assistant : Alperen Dalkıran
Support E-Mail : 2xx@ceng.metu.edu.tr
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 1
Objectives
• In this chapter, you will learn:
– Introduction to Python:
* Numbers and Boolean values in Python,
* Container data in Python
- str
- tuple
- list
- dict
- set
* Mutable - immutable data;
* Aliasing problem
- Labs starting next week.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 2
Dive into Python

• How a computer works,


• How we solve problems with computers,
• How we can represent data in binary,

We are ready to interact with Python

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 3


Dive into Python

• The Python interpreter waits for our


computational demands if not executing
something already.
• Those demands that describe an
algorithm have to be expressed in
Python as a sequence of ‘actions’.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 4


Dive into Python

Each Python action can serve two broad


purposes
• Creating or modifying data
- Perform sequential,
- Conditional or
- Repetitive
execution on the data, and produce other
data.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 5


Dive into Python

Interacting with the environment:


Creating or modifying data
- Usually involve interacting with the
user,
- The peripherals of the computer to take
in (input) data or take out (output) data.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 6


Expression

• An expression specifies a calculation,


which, when evaluated (performed),
yields some data as a result. An
expression can consist of:
- Basic data or container data,
- Expressions involving operations
among data and other expressions,
- Functions acting on expressions.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 7


Statement

• A statement does not return data as a


result and can be either basic or
compound:
- Compound statements are
composed of other statements and
- Executing the compound statement
means executing the statements in
the compound.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 8


Naming and Printing Data

Variables:
• In programming languages, we can
give a name to data and use that
name to access

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 9


Naming and Printing Data

Printing data:
• Python provides the print() function to
display data items on screen.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 10


What is Data?
CPU can only understand two types of data:
• Integers numbers (int in short)
• Floating point numbers (float in short)
The following are not directly understandable
by a CPU:
• Characters (‘a’, ‘A’, ‘2’, …)
• Strings (“apple”, “banana”, …)
• Complex Numbers
• Matrices
• Vectors
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 11
What is Data?
But, programming languages can
implement these data types

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 12


Basic Data in Python
Basic number types in Python
• Integers numbers (int in short)
• Floating point numbers (float in short)
• Complex numbers

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 13


Basic Data in Python
Basic number types in Python
• Integers numbers (int in short)
- As we are used to from your math
classes,
- Have any number of digits (Unlimited
size) in Python
- The internal mechanism of Python
switches from the CPU-imposed fixed-size
integers to some elaborated big-integer
representation silently when needed.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 14
Basic Data in Python
Basic number types in Python
• Floating point numbers (float in short)
- IEEE754 standard (32bit, 64bit)
- The scientific notation (a×10b) to write
floating point numbers.
- float 0.0000000436 can be written in
scientific notation as 4.36×10−8 and in
Python as 4.36E-8 or 4.36e-8

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 15


Basic Data in Python
Basic number types in Python
• Complex numbers
- Can be created by using j after a floating
point number (or integer) to denote the
imaginary part.
- e.g. 1.5-2.6j for the complex number
(1.5+2.6i).

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 16


More on Integers
int data type for integers and
float data type for floating point numbers.

indicates type int.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 17


More on Integers
• In Python version 3,
- integers do not have fixed-size
representation (unbounded
representation) and their size is only
limited by your available memory.
• In Python version 2,
- There were two integer types:
- int, which used the fixed length
representation supported by the CPU,
- long type, which was unbounded.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 18
More on Floats
• Python uses the 64-bit IEEE754
standard, which allows representing
numbers in the range
• [2.2250738585072014E-308,
1.7976931348623157E+308].

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 19


Useful Operations on Numbers
• abs(<Number>): Takes the absolute
value of the number.
• pow(<Number1>, <Number2>): Takes
the power of <Number1>, i.e.
<Number1><Number2>
• round(<FloatNumber>): Rounds the
floating point number to the closest integer.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 20


Useful Operations on Numbers
Functions from the math library:
• type(<data>) function
• sqrt(),
• sin(),
• cos(),
• log(), etc.
(see the Python documentation for a full
list).

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 21


Useful Operations on Numbers
Functions from the math library (Numeric and
Mathematical Modules):
• numbers — Numeric abstract base classes
• math — Mathematical functions
• cmath — Mathematical functions for complex
numbers
• decimal — Decimal fixed point and floating point
arithmetic
• fractions — Rational numbers
• random — Generate pseudo-random numbers
• statistics — Mathematical statistics functions

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 22


Useful Operations on Numbers
This requires importing from the built-in
math library first as follows:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 23


Boolean Values
• Provides True and False.
For example,

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 24


Boolean Values
• Python converts several instances of other data
types to some certain boolean values, if used in
place of a boolean value. For example,
- 0 (the integer zero)
- 0.0 (the floating point zero)
- "" (the empty string)
- [] (the empty list)
- {} (the empty dictionary or set)
are interpreted as False.
• All other values of similar kinds are interpreted
as True.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 25
Useful Operations with Logical Operators
• negation or inverse, and and or
operations. For example,

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 26


Useful Operations with Logical Operators
• logical and
- Returns true if both conditions are true
• logical or
- Returns true if either of its conditions
are true
• logical not, logical negation
- Reverses the truth/falsity of its condition
- Unary operator, has one operand

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 27


Useful Operations with Logical Operators
• Useful as conditions in loops

Expression Result
true and false false
true or false true
not false true
not true false

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 28


Useful Operations with Logical Operators
• Useful as conditions in loops

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 29


Useful Operations with Logical Operators

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 30


Problems with Precedence

• The precedence of some operators


produces problems when they create
behaviours which are unexpected.

31
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python
Decision Making:
Equality and Relational Operators
Solution to Precedence Problems
When in doubt…

Use parentheses!!!

Better still, use parentheses anyway


- You may not be in doubt, but the next
reader may be

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python


Container Data

• Up to this point we have seen the basic


data types. Certainly needed for
computation.
• But many world problems for which,
- Vectors,
- Matrices,
- Ordered and unordered sets,
- Graphs,
- Trees

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 33


Container Data
• Vectors and matrices are used in
almost all simulations/problems of the
physical world;
• Sets are used to keep any property
information as well as orders of items,
equivalences;

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 34


Container Data
• Graphs are necessary for many spatial
problems;
• Trees are vital to representing
hierarchical relational structures, action
logics, organizing data for a quick
search.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 35


Container Data

Five container types for these:,


• String ("str"),
• List ("list"),
• Tuple ("tuple"),
• Dictionary ("dict"),
• Set ("set")

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 36


Container Data

Five container types for these:,


• String ("str"):
 Hold a sequence of characters or
only a single character.
 Can not be modified after creation.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 37


Container Data

Five container types for these:,


• List ("list"):
 Hold ordered sets of all data types
(including another list).
Elements can be modified after
creation.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 38


Container Data

Five container types for these:,


• Tuple ("tuple"):
Very similar to the list type but the
elements cannot be modified
after creation (similar to strings)..

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 39


Container Data

Five container types for these:,


• Dictionary ("dict"):
Very efficient method to form a
mapping from a set of numbers,
booleans, strings and tuples to
any set of data.
Dictionaries are easily modifiable
and extendable.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 40


Container Data

Five container types for these:,


• Dictionary ("dict"):
Querying the mapping of an
element to the ‘target’ data is
performed in almost constant time
(regardless of how many elements
the dictionary has).
In Computer Science terms, it is a
hash table.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 41


Container Data

Five container types for these:


• Set ("set"):
Be equivalent to sets in
mathematics.
The element order is undefined.
(We deemphasize the use of set).

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 42


Sequential Containers

• String, List, Tuple:


- Consist of consecutive elements
indexed by integer values
Starting at 0.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 43


Sequential Containers

• Dictionary:
- Is not sequential.
- Element indexes are arbitrary.

• All these containers have external


representations which are used in
inputting and outputting them (with all
their content).

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 44


Mutability vs. Immutability

• mutable:
- After created-just can wholly
destroyed.
- But cannot change or delete their
individual elements.
- Strings and Tuples are immutable.
- Lists, Dictionaries and Sets are
mutable.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 45


Mutability vs. Immutability

• immutable:
- Adding new elements and changing
or deleting existing ones is possible.
- Lists, Dictionaries and Sets are
mutable.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 46


Accessing elements in s-Containers

• All containers (except set) reveal their


individual elements by an indexing
mechanism with brackets:
- The index is an ordinal number
where counting starts with zero.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 47


Accessing elements in s-Containers

- A negative index (usable only on


s-containers) has a meaning that
the (counting) value is relative to the end.
- A negative index can be converted to a
positive index by adding the length of the
container.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 48
Slicing in s-Containers

• Accessing multiple elements of an s-


container is possible via the slicing
mechanism, which specifies a starting
index, an ending index and an index
increment between elements.

-.
-

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 49


Slicing in s-Containers

- The element at the start index is the


first to be accessed.
- The end index is where accessing
stops (the element at the end index is not
accessed – i.e. the end index is not
inclusive).
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 50
Slicing in s-Containers

- It is also possible to optionally define


an increment (jump amount) between
indexes.
- After the element at [start] is accessed
first, [start + increment] is accessed next.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 51


Slicing in s-Containers

- After the element at [start] is


accessed first, [start + increment] is
accessed next. This goes on until the
accessed position is equal or greater than
the end index.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 52


Slicing in s-Containers

- For negative indexing, a negative


increment has to work from the bigger
index towards the lesser,
so (start index > end index) is expected.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 53


Accessing elements in s-Containers

• If the s-container is immutable


(e.g. string and tuple containers) then
slicing creates a copy of the sliced
data.
• If the s-container is mutable
(i.e. the ‘list’ container) then slicing
provides direct access to the original
elements and
• Therefore, they can be updated, which
updates the original s-container.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 54
Common Operations on Containers

mutable immutable extandable index sequential


String ("str
str"),
str X 0
List ("list
list"),
list X 0
Tuple ("tuple
tuple"),
tuple X 0
Dictionary ("dict
dict"),
dict X X arbitrary not sequential
Set ("set
set")
set X NOT

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 55


Common Operations on Containers

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 56


Common Operations on Containers

1. Number of elements
2. Concatenation
3. Repetition
4. Membership

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 57


Common Operations on Containers

1. Number of elements
- len() is a built-in function
- The count of elements in the
container.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 58


Common Operations on Containers

2. Concatenation
- String, Tuple and List data types
can be combined using ‘+’ operation.

- Where the containers need to be of


the same type.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 59


Common Operations on Containers

3. Repetition
- String, Tuple and List data types
can be combined using ‘*’ operation.

- Where the container is copied ‘’ many


times.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 60


Common Operations on Containers

4. Membership
- All containers can be checked for
whether they contain a certain item as
an element using ‘in’ and ‘not in’
operation.
- The result is either True or False.
- For dictionaries in tests if the domain set
contains the element,
- For others it simply tests if element is a
member.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 61
Strings
• Hold a sequence of characters.
• It is a container where each element is a
character.
• Python does not have a special
representation for a single character.
Characters are represented externally as
strings containing a single character only

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 62


Strings
• Enclosing the character sequence between a
pair of quotes (') or
• Double quotes (").
• A string surrounded with triple double
quotes (""" . . . """) allows to have any
combination of quotes and line breaks within
a sequence.
• Python will still view it as a single entity.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 63


Strings
.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 64


Strings
• The backslash (\) is a special character in
Python strings, also known as the escape
character.
• Prefixing a special character with (\) turns it
into an ordinary character. This is called
escaping.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 65


Strings
• The backslash (\) is a special character in
Python strings, also known as the escape
character.
• It is used in representing certain, the so
called, unprintable characters:
- (\t) is a tab,
- (\n) is a newline,
- (\r) is a carriage return.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 66


Strings
.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 67


Strings
• The backslash (\) is a special character in
Python strings, also known as the escape
character.
• (\') is the single quote character.
• 'It\'s raining'  It's raining
• (") can be escaped:
- "\"hello\""  "hello"

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 68


Examples with Strings

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 69


Examples with Strings

• Strings are immutable.


• An attempt to change a character in a
string will fail.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 70


Useful Operations on String

• Creation
- In addition to using quotes for string
creation, the str() function can be used to
create a string from its argument.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 71


Useful Operations on String

• Concatenation, repetition and


membership:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 72


Useful Operations on String

• Deletion from and Insertion to


strings:
- Since strings are immutable, this is
not possible.
- The only way is to create a new
string, making use of slicing and
concatenation operation (using +), then
replacing the new created string in
same place of the former one.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 73


Useful Operations on String

• Deletion from and Insertion to


strings:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 74


List and Tuple

• Both data types are sequential


containers:
- Contain any other data type (including
other tuples or lists) as elements.
- Tuples are immutable (after being
created, it is not possible to change,delete
or insert any element)
- Lists are mutable.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 75


List and Tuple

• Lists are created by enclosing


elements into a pair of brackets and
separating them with commas,
e.g. ["this", "is", "a", "list"].
• Tuples are created by enclosing
elements into a pair of parentheses
e.g. ("this", "is", "a", "tuple").
• The elements can be any data (basic or
container).
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 76
List and Tuple

• Lists

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 77


List and Tuple

• Tuples can become list members as


well, or vice versa:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 78


List and Tuple
• Lists using is generally prefered over tuples
since they allow changing elements.
• Lists (and tuples) are used whenever there is a
need for an ordered set. Here are a few use
cases for lists and tuples.
- Vectors
- Matrices
- Graphs
- Board game states
- Student records, address book, any inventory
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 79
Useful Operations on Lists and Tuples

• Deletion from lists:


1. Assigning an empty list to the slice
that is going to be removed.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 80


Useful Operations on Lists and Tuples

• Deletion from lists:


2. Using the del statement on the slice
that is going to be removed.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 81


Useful Operations on Lists and Tuples

• Insertion into lists:


1. Using assignment with a degenerate
use of slicing.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 82


Useful Operations on Lists and Tuples

• Insertion into lists:


2. The second method can insert only
one element at a time, and requires
object-oriented features, which
will be covered later.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 83


Useful Operations on Lists and Tuples

• Insertion into lists:


2. The second method can insert only
one element at a time, and requires
object-oriented features, which will be
covered later.
- Takes two parameters: The first
parameter is the index where the item
will be inserted and the second
parameter is the item to be inserted.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 84


Useful Operations on Lists and Tuples

• Data creation with "tuple()" and


"list()" functions:
Similar to other data types, tuple and
list data types provide two functions for
creating data from other data types.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 85


Useful Operations on Lists and Tuples

• Concatenation and repetition with


"tuple()" and "list()" functions:
Similar to strings, + and * can be used
respectively to concatenate two
tuples/lists and to repeat a tuple/list
many times.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 86


Useful Operations on Lists and Tuples

• Membership:
Similar to strings, in and not in
operations can be used to check
whether a tuple/list contains an
element.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 87


Useful Operations on Lists and Tuples

• Membership:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 88


Useful Operations on Lists and Tuples

• Example: Matrices as Nested Lists:


In many real-world problems, we often
end up with a set of values that share
certain semantics or functionality, and
benefit from representing them in a
regular grid structure that we call
matrix.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 89


Useful Operations on Lists and Tuples

• Example: Matrices as Nested Lists:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 90


Useful Operations on Lists and Tuples

• Example: Matrices as Nested Lists:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 91


Useful Operations on Lists and Tuples

• Example: Matrices as Nested Lists:


How we can represent matrices in Python.

Each row is represented as a list and a


member of the outer list.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 92
Dictionary

• Container data type where accessing


items can be performed with indexes
that are not numerical:
- Indexes are called keys.
- Stores an element (value) for each
key.
- Mapping from keys to values

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 93


Dictionary

• Mapping from keys to values

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 94


Dictionary

• Represented as key-value pairs, each


separated by a column sign (:) and all
enclosed in a pair of curly braces.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 95


Dictionary

• Similar to other containers, we usually


store containers under a variable. Let us
assume the dictionary above was
assigned to a variable with the name
conno and look at some examples.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 96


Useful Operations on Lists and Tuples

• remove from – insert to


mappings a dictionary:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 97


Useful Operations on Lists and Tuples

• remove from – insert to


mappings a dictionary:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 98


Useful Operations on Lists and Tuples

• remove from – insert to


mappings a dictionary:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 99


Useful Operations on Lists and Tuples

• remove from – insert to


mappings a dictionary:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 100


Dictionary

• The benefit of using a dictionary is ‘timewise’. The


functionality of a dictionary could be attained by using
(key, value) tuples inserted into a list. Then, when you
need the value of a certain key, you can search one-
by one each (key, value)-tuple element of the list until
you find your key in the first position of a tuple
element.
• However, this will consume a time proportional to the
length of the list (worst case). On the contrary, in a
dictionary, this time is almost constant.
• Moreover, a dictionary is more practical to use
since it already provides accessing elements in a key-
based fashion.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 101
Useful Operations with Dictionaries

• len() and
• membership (in and not in) operations that we have
seen above.
• <dictionary>.values() and
• <dictionary>.keys() to obtain lists of values and keys
respectively.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 102


Set

• Created by enclosing elements into a pair of


curly-braces and separating them with commas.
• Any immutable data type, namely a number, a string
or a tuple, can be an element of a set.
• Mutable data types (lists, dictionaries) cannot be
elements of a set.
• Being mutable, sets cannot be elements of a sets.

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 103


Dictionary

• Frozenset:
- An immutable version of the set type.
- Can be constructed using the
frozenset() function.

- Being immutable, frozensets can be a


member of a set or a frozenset.
Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 104
Useful Operations with Sets
• len() and
• membership (in and not in) operations
that we have seen above.
• sets and frozensets support the
following operators:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 105


Useful Operations with Sets
• The following are only applicable with
sets (and not with forezensets) as they
require a mutable container:

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python 106


Questions

Fall 2023 Hüseyin Sayın - Ceng240 – Lecture-3 – Introduction to Python

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy