Chapter 1: Python basic
Lecturer: Nguyen Tuan Long, Phd
Email:
[email protected] Mobile: 0982 746 235
Chapter 1: Python basic 2
1.4. Python for loops and Tuple, Set
• For loops
• Making Numerical Lists
• Working with Part of a List
For loop 3
Looping Through an Entire List A for loop is used for iterating over a
collection (or sequence) (that is either a list,
Collection a tuple, a dictionary, a set, or a string)
Define a for loop
indent
Repeat
For loop
For loop 5
Looping Through a String
For loop
Avoiding Indentation Errors
For loop
Practice
4-1, 4-2
Making Numerical Lists
Using the range() Function Start Stop
Start
Stop
1
Using range() to Make a List of Numbers
Start = 0
Making Numerical Lists
Start Stop Step
Step • First 10 square numbers into a list
Making Numerical Lists
Simple Statistics with a List of Numbers
The dir() function: returns all properties and methods of the specified object, without the values.
Making Numerical Lists
List Comprehensions
• First 10 square numbers into a list
Practice
4-3,…, 4-9
Working with Part of a List
Slicing a List
slice [start: stop: step]
Start Stop Step
Working with Part of a List
Looping Through a Slice
Working with Part of a List
Copying a List
Working with Part of a List
Practice
4-10, 4-11
Tuples
Defining a Tuple: A tuple looks just like a list
• except you use parentheses
instead of square brackets.
• except you can't change the values in a tuple once
it's defined
Tuples
Looping through a tuple
Overwriting a tuple
Practice
4-13
Sets
Defining a Set: A set is a collection which is unordered and
unindexed. In Python sets are written with curly brackets.
Change items: you cannot change its items.
Add: use the add() or update() methods
Sets
The Length of a Set
Note: If the item to remove does not
exist, discard() will NOT raise an error.
Remove Item
Note: Sets are unordered, so when using
the pop() method, you will not know
which item that gets removed.
Sets
• The clear() method empties the set:
Join Two Sets
• The union() method returns a new set with all items from both sets
Sets
Converting: use the set() function.
Practice
1. Create a set from a string, list and tuple.
2. How many letters and words are there in the following message?
message = ‘’’
(import this)
‘’’