Lecture 3 Python Multivalue Data Types Functions - Hadi - Updated
Lecture 3 Python Multivalue Data Types Functions - Hadi - Updated
Lecture 3
Source 1: Fundamentals of Python Programming.
Source 2: Python Data Science Handbook
Based on slides prepared By: Dr. Zaher Merhi
1
Outline
• Jupyter Notebook
• Data structures: list, tuple, dictionary and set
• Functions
2
Launching Jupyter NoteBook
3
Help function
• For directly executing the commands in a cell, press CTRL-ENTER
• For directly executing the commands in a cell and creating a new cell after it,
press ALT-ENTER
• Help Function: displays information about the function
4
Help function
• Another way.
5
TAB completion
• Tab completion for variable names: an_<TAB>
6
Magic commands
• %history
7
Magic commands
• All magic commands have % before them
• %timeit command
8
Magic commands
9
Plotting
• Plots and figures can be displayed in Jupyter Notebook
10
List
• A list holds an ordered collection of items i.e. a sequence of objects
• Lists are variable length and their contents can be modified
11
List
• A list can be generated from a range object:
12
List: Adding elements
• Adding elements: append() adds an element to the end of a list
13
List: Removing elements
• Removing is done by pop or remove
• Pop removes the last element and returns it
• Pop also takes the index of the element to be removed and returns it:
14
List: Removing elements
• Remove takes as input the value to be removed and returns the first occurrence
15
List: in keyword
• Check if an element is in list
16
List: Concatenation
• List concatenation
17
List: Sorting
• Sorting: sort() modifies the list
• sorted(): returns a sorted list without modification the input list, same arguments
as sort()
18
List: Sorting
• Sort key is useful, it has the ability to pass a secondary sort key which
is function that produce a value to use to sort the object
19
List: Slicing
• Start:Stop Start ≤ index ≤ Stop-1
3 to end
20
List: Slicing
• Negative indices slice the sequence relative to the end
• A step can also be used to indicate the step between each slice
21
Lists
• Enumeration: Built in function which returns the sequence(i, value)
• Instead of doing something like this
• Example:
22
List: zip()
• zip(): pairs up elements of a number of lists, tuple or other sequenced
to create a list of tuples
23
List: zip()
• A common example of zip is to iterate over multiple sequences
24
Tuple
• A Tuple is a fixed-length immutable sequence of python objects.
• The easiest way is with comma-separated sequence of values:
25
Tuple: Converting to a tuple
• Function tuple() is used to convert to a tuple
• Convert a list to a tuple:
26
Tuple
• A tuple can have different types of elements:
27
Tuple
28
Tuple Operations
• Concatenation: Creates a new tuple. Remember: a tuple is immutable.
29
Tuple Operations
• Count: counts the number of occurrences of a value in a tuple
• Unpacking
30
Tuple Operations
• Swap
• Unpacking
31
Tuples and lists of length 0 and 1
32
Dictionary
• Dict is an important data structure in python
• A common name is hash map or associative array
• It is a flexibly sized collection of key-value pairs where key and vales are
objects
• Can be declared using curly brackets
33
Dictionary
• You can access, insert or set elements using same syntax as lists or
tuples
34
Dictionary
35
Dictionary: Removing elements
• Using del
• Using pop
36
Dictionary: keys() and values()
• The keys() and values() methods give you iterators of the dict’s keys
and values
• Key values pairs are not in any particular order but these functions output the
keys and values in the same order
37
Creating dicts from sequences
• Enumeration example:
38
Creating dicts from sequences
• It is common to occasionally end up with two sequences that you
want to pair up element wise in a dict
• You might write the code like this
39
Default values
• Getting value from a dict
40
Default values
• It is very common to have something like this
• dict method get and pop can take default values to be returned, so
the if else block can be written as:
41
Example
• What does this code do?
• Output
42
Set
• A set is am unordered collection of unique elements
• You can think of them like dicts but keys only and no values
• A set can be created in two ways by set function if set literal with
curly brackets.
43
Set
• Union • Intersection
44
Set Operators
45
Set Examples
46
List, set and dict comprehensions
• Comprehensions allows to form a new list by filtering the elements of
a collection. They take the basic form
48
Functions
• Uses keyword def and return:
• You can pass arguments in any order if you match the name:
• You may find yourself doing this when the function return one object
namely a tuple and you unpack it in the result variables
• In case of dict
50
Exercises
1. Write a script that sorts a list of integers in descending order. Hint: use sort
method and provide an appropriate key function
2. Write a function called is_prime that checks if an integer is prime or not.
• Use this function to generate a list of the first 20 prime integers.
• How long time it takes to generate this list?
3. Reverse Integer: Given an integer, return the integer with reversed digits.
• Note: The integer could be either positive or negative.
Hint: you can cast the integer into a string. A string can be treated as a list of characters
4. Average Words Length: For a given sentence, return the average word length.
• Note: Remember to remove punctuation first.
5. Valid Palindrome: Given a non-empty string s, judge whether it is a
palindrome.
• A palindrome is a word or group of words that is the same when you read it forwards
from the beginning or backwards from the end: "Refer" and "level" are palindromes 51
Exercises
6. Monotonic Array: Given an array of integers, determine whether
the array is monotonic or not.
7. Move Zeroes: Given a list of numbers, write a function to move all
zeroes to the end of it while maintaining the relative order of the
non-zero elements.
8. Code up a function to compute a cipher on text input.
• Hint: Think about using a dictionary
9. Write a code that extracts all possible combination of 2 argument
tuples
52