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

Week2Session5 - Lists and Dictionaries2

Uploaded by

VJ Molina
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 views38 pages

Week2Session5 - Lists and Dictionaries2

Uploaded by

VJ Molina
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
You are on page 1/ 38

NIT1102

Introduction to Programming

Session 5 - Lists and Dictionaries

Grace Tan
[email protected]
1-1
Outline

1. Lists

2. Defining Simple Functions

3. Case Study: Generating


Sentences

4. Dictionaries

1-2
Lists
A list is a sequence of data values called items or elements.
Some real-world examples of lists:
◦ A shopping list for the grocery store
◦ A to-do list
◦ A roster for an athletic team
◦ A guest list for a wedding
◦ A recipe, which is a list of instructions
◦ A text document, which is a list of lines
◦ The words in a dictionary
◦ The names in a phone book
Each item in a list has a unique index that specifies its
position.
Index of the first item is 0
Index of the last item is the length of the list minus 1
1-3
List Literals and Basic Operators
A list is written as a sequence of data values separated by
commas.

use other lists as elements in a list

Elements in a list are evaluated

1-4
List Literals and Basic Operators
Build lists of integers using the range and list functions

Using function len and the subscript operator []

1-5
List Literals and Basic Operators
Concatenation (+) and equality (==)

print the contents of a list without the brackets and commas

in operator to detect the presence or absence of element:

1-6
List Literals and Basic Operators

1-7
Replacing an Element in a List
subscript operator is used to replace an element at a given
position

replace each number in a list with its square:

1-8
Replacing an Element in a List

Example 1: converted to uppercase letters within the list

1-9
Replacing an Element in a List
Example 2:
replaces the first three elements of a list with new ones

Write code to replace elements 2 to 4 with


new values of 200, 300 and 400

1-
10
Inserting and Removing Elements

Example 3:

1-11
Inserting and Removing Elements
Example 4:
append and extend
adds the new element
to the end of the list

pop is used to remove an


element at a given
position, or at the end of
the list if the index is not
provided.

1-
12
Searching and Sorting
Search a list use the in operator to test for presence and then
the index method if this test returns true

method sort mutates a list by arranging its elements in


ascending order

1-
13
Aliasing and Side Effects
Do you notice any thing interesting/strange thing?

side effect: second element of the first list is replaced,


the second element of the second list is replaced too
Variables first and second refer to the exact same list object

1-
14
Aliasing and Side Effects
prevent aliasing: create a
new object and copy the
contents of the original to
it.

first and third refer to


two different list objects,

1-
15
Tuples
A tuple is a type of sequence that resembles a list, except that,
unlike a list, a tuple is immutable. Enclose tuple elements in
parentheses instead of square brackets

Use a tuple instead of list, when you foresee using a list


whose structure will not change.
1-
16
List Practices
Class Practice 1:

7
7
3

[5, 3]
False
[5, 3, 7, 2, 10, 5]

(5, 3, 7)

1-
17
Outline

1. Lists

2. Defining Simple Functions

3. Case Study: Generating


Sentences

4. Dictionaries

1-18
Simple Function Definitions
A function consists of a header and a body.

a single return statement, which simply returns the


result of multiplying its argument

Using the function

1-
19
Simple Function Definitions
Example 5:
average value in a list of numbers.

Using the function

1-
20
Simple Function Definitions
Example 6: Boolean function

1-
21
Defining a main Function
A special function named main that serves as the entry point

no particular order for functions in the script, as long as


the main is called at the very end of the script

1-
Introduction 22
Function Definition Practice
Class Practice 2:
Define a function named even. This function expects a number
as an argument and returns True if the number is divisible by 2,
or it returns False otherwise

Sample Solution:

1-
23
Outline

1. Lists

2. Defining Simple Functions

3. Case Study: Generating


Sentences

4. Dictionaries

1-24
Case Study: Generating Sentences
Request: Write a program that generates sentences.
Analysis: simple grammar rules for our example

proposed user interface

1-
25
Case Study: Generating Sentences
Design:
Function for Sentence: Noun phrase and Verb phrase are
concatenated

Noun phrase picks an article and a noun at random from


the vocabulary, concatenates them, and returns the result

Variables articles and nouns refer to collections of these


parts of speech, function random.choice returns a random
element from such a collection. 1-
26
Case Study: Generating Sentences
verbsPhase randomly pick a verb, then concatenate with
nounPhrase and prepositionalPhrase

Design your code for prepositionalPhrase

1-
27
Case Study: Generating Sentences
main function drives the program with a count-controlled loop

The data structure used to represent a collection of words


should allow the program to pick one word at random. Let’s
use tuple because the data does not change.

1-
28
Case Study: Generating Sentences
Implementation

1-
29
Outline

1. Lists

2. Defining Simple Functions

3. Case Study: Generating


Sentences

4. Dictionaries

1-30
Dictionaries
A dictionary organizes information by association,
its data structure is called tables or association lists

A Python dictionary is written as a sequence of key/value


pairs separated by commas

The entire sequence of entries is enclosed in curly braces { and }.


A colon : separates a key and its value

1-
31
Adding Keys and Replacing Values
creates an empty dictionary and adds two new entries

replace a value at an existing key,

1-
32
Accessing Values
subscript to obtain the value associated with a key.

Test for existence of a key using get function with a


default value of None:

Default value is returned if the key job is absent 1-


33
Removing Keys
method pop is used to delete an entry from a dictionary

If the key is in the dictionary, it is removed, and its


associated value is returned.
Otherwise, the default value is returned.

If pop is used with just one argument, and this key


is absent from the dictionary, Python raises an error.
1-
34
Traversing a Dictionary
for loop is used with a dictionary

method items() to access a list of dictionary entries

tuple of variables can then access the key and value of each entry
in this list within a for loop

1-
35
Dictionary Operations

1-
36
Dictionary Practice
Class Practice 3:

35
Nothing (return None with print function)
2
dict_keys(['b', 'a'])
dict_values([20, 35])
20
{'a': 35}

1-
37
References
This lecture was developed based on Chapter 5 in:

Kenneth A. Lambert (2019).


Fundamentals of Python: First
Programs 2nd Cengage Learning.

1-
Introduction 38

You might also like