0% found this document useful (0 votes)
22 views48 pages

Lesson 8 Lists and Tuples

Lesson 8 covers Python data structures, specifically lists and tuples, highlighting their similarities and differences. It explains how to create, manipulate, and access elements within lists, as well as the immutable nature of tuples. The lesson also includes exercises to reinforce understanding of these concepts.

Uploaded by

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

Lesson 8 Lists and Tuples

Lesson 8 covers Python data structures, specifically lists and tuples, highlighting their similarities and differences. It explains how to create, manipulate, and access elements within lists, as well as the immutable nature of tuples. The lesson also includes exercises to reinforce understanding of these concepts.

Uploaded by

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

Lesson 8: Python Data Structures 1:

Lists and Tuples


Introduction to Python Programming
Lesson 8: Python Data Structures 1:
Lists and Tuples

Lesson Overview

Introduction

The List Structure

Additional List Features

Tuples and Graphics

Review
Introduction

3
Introduction


If you have programming experience in another
language, then you're probably familiar with
arrays, which offer a way to store a sequence of
data that's usually related.

In Python – there is a list structure which offers
similar capability.

Python also provides a tuple structure that is
similar to a list but with a twist: once a tuple is
created, its values cannot be changed.

4
The List Structure: Basics


A Python list is similar to an array in other
languages

It’s a variable that can store an ordered
collection of values.

You can get to an individual element (item) in
the list through the list's name and a unique
number specifying the location of the element
inside the list.
That number is called the index (or subscript).

Like Strings – Index starts at zero.


5
The List Structure: Basics


Here’s a graphical representation of how a
simple variable (count) and a list variable
(days_of_week) are stored in memory.

For example ‘Tue’ is located at days_of_week[2]


6
The List Structure: Creating a List


You can create lists by simply enclosing you’re
list of data in square brackets.
days_of_week = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
nums=[10, 20, 30, 40]
var=['spam', 2.0, 5, [10, 20]]
A comma separates each of the values.

Once you create them you can access the values


by the indexes like nums[3], var[0].

7
Looping Through a List


Since you reference
each value in the list via
an index you can simply
loop through a list.

You can access the
length of a list by using
the len function you
used for strings.

len(days_of_week) will give 7.

8
Looping Through a List

9
List properties.


Lists are ordered.

Lists can contain any arbitrary objects.

List elements can be accessed by index.

Lists can be nested to arbitrary depth.

Lists are mutable.

Lists are dynamic.

10
Manipulating List Contents


To change one of the values in a list you can
simply access that value via an index and assign
a new value to it.
days_of_week[0]=”Sunday”

Python Lists have some significant difference
from arrays in other languages such as giving
you the ability to work with an entire list as a
single unit.

For example you can print the entire list by this:
print(days_of_week)

11
Manipulating List Contents

12
Slicing and Nesting Lists


Just like in strings you can slice lists by using the
string variable name and then place a number, a
colon, and another number inside square
brackets.
print(days_of_week[2:5])

The value at the second index won’t be included
in the slice.

You can leave out the last index to include the
last element.
print(days_of_week[2:])

13
Nesting a List


Another interesting
feature of lists is that
you don’t have to store
the same data type
inside each element.

This means you can put
lists inside of list.

You can access
elements in nested lists
by using combination of
indexes.

14
Additional List Features: Adding Items
to the List


One of the great things
about the list variable is
that it enables you to add
new elements to the list at
any time.

You can add elements to
this list anytime you want
using the append function.

Simply place the list variable name, a
dot, the function name, and then the
value you want appended inside
parentheses.

15
Additional List Features: Adding Items
to the List


You can also use the
extend function to add
more than one element
at once.

You just need to pass
the new list to the
function.

You can also add
elements by using
concatenation.

16
Additional List Features: Adding Items
to the List


You can also insert an item at a specific index in
the list.

This is done with the insert function.

This function requires that inside the parentheses
you provide both the index where you want the
value to be stored (first) and the value to be stored
(second).
my_list.insert(3, 'hi there!')
The list not only grows in overall length from this,

but it also increments the index values of the items


with an index value of 3 or higher.
17
Additional List Features: Removing
Items from the List


You can remove items from list by using the
remove() function.

The syntax is as follows:
<list_name>.remove(<value>)

Remember, a call to remove will change the length
of the list and will shift the index value of each
item to the right of the deleted value one position
to the left (that is, decrease each item’s index
value by one).
This will remove the first item with the value

provided.
18
Additional List Features: Finding the
Largest Value


Python provides a
variety of functions for
working with the list
items.

For example, maybe you
have a list of numbers
and want to find out the
biggest or smallest item
in your list. To do that,
use the functions max
and min.

19
Additional List Features: Reversing the
List Order


You can reverse the order
of the elements in you list
by using the reverse()
function.

There are many more
function which operate on
list. You can look at them
by typing help(my_list) or
help(<list object name>).

Like sort(), clear(), pop().

20
Tuples and Graphics: Tuples


The concepts behind lists and tuples are nearly
identical because a tuple is also an ordered
sequence of elements.

Additionally, most of the functions used with a
list can also be used with a tuple.
For example, there's a tuple function len that

gives the length of a list of elements.



You can also use slicing to get a subtuple of an
existing tuple.

21
Tuples and Graphics: Tuples


So what is the difference between lists and
tuples?

First tuple use parentheses.
days_of_week=('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')

Tuples are immutable.
Because of this – it is stored more efficiently in

memory.

Immutability can be desirable sometime.

Some modules pass and return tuples as
arguments.
22
Tuples and Tkinter


Remember the create_text
function and font option in
from the Canvas class?
In the last line font is set

via a tuple.

If you had wanted to
create multiple text
components, each with the
same font, you could have
created the tuple variable
first, and then used it each
time you made a new text
component.

23
Tuples and Tkinter


Here’s a demonstration.

24
Receiving a Tuple from a Function Call


Creating a tuple variable to pass to a function call
can be helpful, but it's just as important to be able
to receive a tuple back from a function call.

If you look through the Canvas' member list,
you'll see that multiple functions return a tuple.

One example of such a function is find_enclosed.
To use this function, you must pass it the
coordinates for a bounding box.

The function then looks at the Canvas and
creates a tuple of all the components completely
enclosed inside that bounding box.
25
Receiving a Tuple from a Function Call


For example - Create a Canvas
that contains three rectangles
stacked vertically with a little
space in between each one as in
the example.

26
Receiving a Tuple from a Function Call

27
Receiving a Tuple from a Function Call

Notice how when returning one


value or no values – python includes


a comma and the parentheses.

This is to indicate that the return
type is a tuple.

You could use this function to print which shapes are
in a particular region of the Canvas. But you could
also take each of those shapes and move them. If you
used the find_enclosed function, you could store that
tuple in memory. Then, when you wanted to move
them, you could simply loop through the tuple and
each time make a call to coords( ) to move it.

28
Exercises.


Write a Python program to convert a tuple to a
string.

29
Exercises.


Solution.

30
Exercises.


Write a program to print the odd numbers in a
list.

31
Exercises.


Solution.

32
Exercises.

Write a program to count the negative and


positive numbers in a list.

33
Exercises.


Solution.

34
Exercises.


Write a program that counts unique values
inside a list.

35
Exercises.


Solution.

36
Exercises.


Write a Python program to check whether an
element exists within a tuple.

37
Exercises.


Solution.

38
Exercises.

39
Exercises.


Solution.

40
Exercises.


Write a program to remove an item from a
tuple.

41
Exercises.


Solution.

42
Exercises.


Write a program that reverses a tuple.

43
Exercises.


Solution.

44
Exercises.


Write a Python program to calculate the
average value of the numbers in a given tuple of
tuples.

45
Exercises.


Solution.

46
Lesson 2 Review

We saw basic Python data structures.


Lists and tuple.


We saw basic syntax on how to create this type.


We also saw some function that are provided by


python to manipulate lists and tuple.



Finally we saw how tkinter uses tuples in it’s
classes.

47
Some exercises:


Modify your temperature and currency converters to
take lists or tuples and create converted lists or
tuples.

Write a function called middle that takes a list and
returns a new list that contains all but the first and
last elements. For example:
>>> t = [1, 2, 3, 4]
>>> middle(t)
[2, 3]

Write a program that does matrix multiplication
using lists. A two dimensional matrix would be a list
like [[1, 2] , [8, 5]]
48

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