Lists - Computing Science

Download Report

Transcript Lists - Computing Science

Lists
Introduction to Computing
Science and Programming I
Lists


To this point we have used simple
variables to store data. One variable
storing a string, int, or some other type of
value.
Using variables can become cumbersome
if you want to store more data. If you
wanted to store the name and id for 10
students you would need twenty separate
variables.
Lists



Python provides a data structure called a
list to store multiple values.
Lists can store values of any data type and
a single list can store values of different
types.
Lists are stored in a variable as with the
other data types.
Lists

Some examples






numberList = [20 , 15 , 10 , 15 , 0]
wordList = [“some”,”words”,”are”,”these”]
boolList = [True, False, True]
mixedList = [“hello”, 1.5, True, “x”, [1,2,3]]
Note the representation for lists, they are
surrounded by square brackets with their
contents separated by commas
Since a list is just another data type, lists can
have lists as members.
Lists

Accessing an element of a list is done in the
same way as accessing a single character from a
string. The first element has index 0.



numbers = [2,4,6,8,10]
numbers[0] is 2, numbers[2] is 6
You can also assign new values to elements of a
list, something you can’t do with a string.



numbers[0] = -5
numbers[4] = 0
#now numbers is [-5,4,6,8,0]
Lists

The + and * operators work with lists as
they do with strings.

+, “concatenation”


[2, 4, 8] + [16, 32, 64] is [2, 4, 8, 16, 32, 64]
*

[1,2,3] * 3 is [1,2,3,1,2,3,1,2,3]
Lists

The len() function used with strings will
tell you how many elements a list
contains.



myList = [1, 4, 11, 13]
len(myList) returns 4
This allows us to loop through the
elements of a list as we have with strings.
for i in range(len(myList)):
print myList[i]
Lists

Here are a couple more basic functions for
manipulating lists.

append is used to add a single element to the
end of a list.
names = [“Chris”,”Matt”,”Steph”]
 names.append(“Jesse”)
 names.append(“Rob”)


del can be used to delete specific elements

del names[2]
Lists vs Strings



Strings act in a lot of ways like a list of
characters, but there are important
differences.
You can’t make changes to a string,
adding, removing, or changing characters,
without recreating the entire string.
We’ll look at these differences more a bit
later.
Lists in For Loops

All of the for loops we’ve written so far
have been of the form
for i in range(5):
….

All the range function does is return a list
of numbers, [0,1,2,3,4] in this case, and
the code in the loop is run after assigning
each element of the list to i
Lists in For Loops

You can use any list when you write a for
loop. Every element of the list will be
assigned to the variable you give and the
code will be executed.
for x in [1,2,3]:
print x
cities = [“Toronto”,”Vancouver”,”Montreal”]
for city in cities:
print city
Slices


We’ve already seen how to access single
elements of a list by using their index.
You can access multiple elements of a list
at the same time by using the process
called slicing.
Slices

Typical slices
numbers = [“one”, “two”, “three”, “four”]
numbers[0] is “one”
numbers[0:2] is [“one”, “two”]
numbers[1:4] is [“two”, “three”, “four”]

Notice that the slice [a:b] gives the
element a through the element b-1. This
is the same logic the range function uses
if you give it two numbers.
Slices

If you don’t give a beginning or ending
index, the slice will start at the beginning
or end of the list.
numbers = [“one”, “two”, “three”, “four”]
numbers[:2] is [“one”, “two”]
numbers[1:] is [“two”, “three”, “four”]
Slices

You can use negative numbers as indexes.
In this case Python starts counting
backwards from the end of the list.
[“one”, “two”, “three”, “four”]
index: 0
1
2
3
index: -4
-3
-2
-1
Slices

A couple examples with negative indexes
numbers = [“one”, “two”, “three”, “four”]

In this case [0:2] and [-4:-2] are identical
numbers[-4:-2] is [“one”, “two”]

[:-1] gives all but the last element
numbers[:-1] is [“one”, “two”, “three”]
Slices

You can assign lists to a slice.
numbers = [“one”, “two”, “three”, “four”]
numbers[1:3] = [“A”, “B”]
numbers now is [“one”, “A”, “B”, “four”]

You don’t have to replace a slice with a list
with the same number of elements
numbers = [“one”, “two”, “three”, “four”]
numbers[1:3] = [“A”]
numbers now is [“one”, “A”, “four”]
Slices

As with single elements you can delete
slices of a list.
numbers = [“one”, “two”, “three”, “four”]
del numbers[1:3]
numbers is now [“one”, “four”]
Slices and Strings

The same rules for slicing lists can be used
for slicing strings. However, you can’t
assign values to a slice of a string.
s = “Hello World”
s[1:5] is “ello”
s[-5:] is “World”
s[1:5] = “i” would cause an error.
For Loops and Strings

For loops can use strings in the same
manner as they use lists.
for c in “abc”:
print c

Each character in the string will be
assigned in turn to the variable c
Strings vs Lists

The central difference between strings and
lists is that a list can be changed in-place,
that is we can alter it without creating a
new list. This can not be done with
strings.
Mutability

The term used to describe this difference
is mutability.


An object such as a list, that can be changed
is mutable.
Strings, which cannot be changed, are
immutable
Mutability
numList = numList + [5]
stars = stars + “*”

In lines of code such as these Python creates an entirely
new list/string and stores it in a variable. The original
list/string is removed from memory
numList.append(5)


Something different is happening here. Instead of
creating an entirely new list we are calling a method of
numList that alters the list.
deleting or assigning new values to an element/slice of a
list also do not cause the list to be recreated from
scratch
Mutability



In general using these methods of altering
a list in-place are more efficient since they
do not require Python to make a copy of
the list to evaluate an expression.
strings, our simple data types (int, Bool…),
and some objects are immutable.
Lists and some other objects are mutable.
References


So far we’ve just looked at variables as
storing a value.
Now we’re going to get into some detail
on how Python handles variables behind
the scenes.
References

Every variable in Python is a reference to a
specific spot in memory where the contents of
the variable are actually stored.
print x+5

When a variable is part of an expression Python
retrieves the contents from the location in
memory specified by the variable. Once it has
them it can complete the expression
References
x=3+6
x=2*n

In lines of code such as these Python
evaluates the expression on the right side,
stores the value in memory, and then has
x point to that place in memory.
References
References

Copying variables




Simple assignment, x = y
Function parameter, print some_function(x)
In these cases Python just copies the location of
memory to the new variable.
That means that Python doesn’t need to copy
the entire contents of a variable which could be
a list containing thousands of elements.
References
References

Aliases



When two variables point to the same location
in memory, as with the last example, they are
called aliases of each other.
With immutable data types this doesn’t cause
any complications because the contents of the
location in memory can’t be changed.
However, with mutable data, such as a list, if
two variables are aliases of the same list,
changes to one variable will be seen by both.
References
References


This aliasing means that if a function takes
a list as an argument, changes to that list
inside the function will be seen outside the
function.
This should be avoided unless the function
makes absolutely clear that a list passed
to it will be changed.
References

Cloning


If you want to make an identical but separate
copy of a variable, you must clone it.
With lists this can be done by doing the
following.
newList = oldList[:]

Since there is no start or end index for the
slice, Python copies the entire list. newList
and oldList now point to separate copies of
the list.