Text stringlengths 1 9.41k |
|---|
print("Let's bake a pie!")
... else:
... print("Oops. No apples.")
...
Oops. No apples.
```
or
```
>>> if 'kiwi' in fruits:
... print("Let's bake kiwi tarts!")
... else:
... |
print("Oops. |
No kiwis.")
...
Let's bake kiwi tarts!
```
This works the same with numbers or with mixed-type lists.
```
>>> some_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> 5 in some_primes
True
>>> 4 in some_primes
False
```
or
```
>>> mixed = (42, True, 'tobacconist', 3.1415926)
>>> 42 in mixed
True
>>> -... |
This method takes some value as an
argument and returns the index of the first occurrence of that element
in the sequence (if found).
```
>>> fruits = ['kumquat', 'papaya', 'kiwi', 'lemon', 'lychee']
>>> fruits.index('lychee')
4
```
However, this one can bite. |
If the element is not in the list, Python will
raise a ValueError exception.
```
>>> fruits.index('frog')
Traceback (most recent call last):
File "/Library/Frameworks/.../code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
ValueError: 'frog' is not in list
```
This... |
Yikes! |
So what can be done?
Later on in this textbook we’ll learn about exception handling, but for
now, here’s a different solution: just check to see if the element is in the
list (or other sequence) first by using an if statement, and then get the
index if it is indeed in the list.
```
>>> if 'frog' in fruits:
... |
print(f"The index of frog in fruits is "
... f"{fruits.index('frog')}")
... else:
... |
print("'frog' is not among the elements in the list!")
```
This way you can avoid ValueError.
###### 10.8 Sequence unpacking
Python provides us with an elegant syntax for unpacking the individual
elements of a sequence as separate variables. |
We call this unpacking.
-----
```
>>> x, y = (3.945, 7.002)
>>> x
3.945
>>> y
7.002
```
Here, each element in the tuple on the right-hand side is assigned to a
matching variable on the left-hand side.
```
>>> x = (2,)
>>> x
2
>>> x, y, z = ('a', 'b', 'c')
>>> x
'a'
>>> y
'b'
>>> z
'c'
... |
If they don’t
match, we get an error, either ValueError: too many values to unpack
or ValueError: not enough values to unpack.
Tuple unpacking is particularly useful by:
- allowing for more concise and readable code by assigning multiple
values to variables on a single line,
- allowing for multiple values to be r... |
We can unpack lists the same way.
```
x, y = [1, 2]
```
But this isn’t used as much as tuple unpacking. |
Can you think why this
may be so?
The reason is that lists are dynamic, and we may not know at runtime
how many elements we have to unpack. |
This scenario occurs less often
with tuples, since they are immutable, and once created, we know how
many elements they have.
-----
###### What if we want to unpack but we don’t care about certain elements in the sequence?
Let’s say we want the convenience of sequence unpacking, but on the
right-hand side we have a... |
In cases like this, we
often use the variable name _ to signify “I don’t really care about this
value”.
Examples:
```
>>> _, lon = (44.318393, -72.885126) # don't care about latitude
```
or
```
>>> lat, _ = (44.318393, -72.885126) # don't care about longitude
```
This makes it clear visually that we’re only conce... |
In these cases, it’s not unusual to see both _ and
```
__ used as variable names to signify “I don’t care.”
```
Examples:
```
>>> _, lon, __ = (44.318393, -72.885126, 1244.498)
```
or
```
>>> lat, _, __ = (44.318393 -72.8851266, 1244.498)
```
or
```
>>> _, __, elevation = (44.318393, -72.8851266, 1244.498)
``... |
For example, this works just fine:
```
>>> _, _, elevation = (44.318393, -72.8851266, 1244.498)
```
In this instance, Python unpacks the first element of the tuple to _, then
it unpacks the second element of the tuple to _, and then it unpacks the
third element to the variable elevation.
If you were to inspect the v... |
In most
languages we’d need to do something like this:
-----
```
int a = 1
int b = 2
// now swap
int temp = a
a = b
b = temp
```
This is unnecessary in Python.
```
a = 1
b = 2
# now swap
b, a = a, b
```
That’s a fun trick, eh?
###### 10.9 Strings are sequences
We’ve already seen another seque... |
Strings are nothing
more than immutable sequences of characters (more accurately sequences
of Unicode code points). |
Since a string is a sequence, we can use index
notation to read individual characters from a string. |
For example:
```
>>> word = "omphaloskepsis" # which means "navel gazing"
>>> word[0]
'o'
>>> word[-1]
's'
>>> word[2]
'p'
```
We can use in to check whether a substring is within a string. |
A substring
is one or more contiguous characters within a string.
```
>>> word = "omphaloskepsis"
>>> "k" in word
True
>>> "halo" in word
True
>>> "chicken" in word
False
```
We can use min() and max() with strings. |
When we do, Python will
compare characters (Unicode code points) within the string. In the case
of min(), Python will return the character with the lowest-valued code
point. |
In the case of max(), Python will return the character with the
highest-valued code point.
-----
We can also use len() with strings. |
This returns the length of the
string.
```
>>> word = "omphaloskepsis"
>>> max(word)
's'
>>> min(word)
'a'
>>> len(word)
14
```
Recall that Unicode includes thousands of characters, so these work with
more than just letters in the English alphabet.
###### Comprehension check
1. |
What is returned by max('headroom')?
2. What is returned by min('frequency')?
3. |
What is returned by len('toast')?
###### 10.10 Sequences: a quick reference guide
Mutability and immutability
Type Mutable Indexed read Indexed write
`list` yes yes yes
`tuple` no yes no
`str` no yes no
###### Built-ins
Type `len()` `sum()` `min() and max()`
`list` yes yes (if numeric) yes, with some restrictio... |
So, for example, sum([1, 1.0, True]) yields three. |
We
cannot sum over strings.
- min() and max() work so long as the elements of the list or tuple
are comparable—meaning that >, >=, <, <=, == can be applied to any
pair of list elements. |
We cannot compare numerics and strings, but
we can compare numerics with numerics and strings with strings.
- We can test whether a value is in a list or tuple with in. |
For example
```
'cheese' in m returns a Boolean.
```
- m.sort(), m.append(), and m.pop() work for lists only. Tuples are
immutable. |
Note that these change the list in place.
- We cannot apply m.sort() if the list or tuple contains elements
which are not comparable.
- We must supply an argument to m.append() (we have to append
_something)._
- m.pop() without argument pops the last element from a list.
- m.pop(i) where i is a valid index ... |
'USA', 'Albania', 'Brazil', 'Gabon',
... 'Ghana', 'UAE', 'India', 'Ireland',
... |
'Kenya', 'Mexico', 'Norway']
```
Let’s say we just wanted the permanent members of the UN Security Council (these are the first five in the list). |
Instead of providing a
single index within brackets, we provide a range of indices, in the form
```
<sequence>[<start>:<end>].
>>> un_security_council[0:5]
['China', 'France', 'Russia', 'UK', 'USA']
```
“Hey! |
Wait a minute!” you say, “We provided a range of six indices! Why
doesn’t this include ‘Albania’ too?”
Reasonable question. |
Python treats the ending index as its stopping
point, so it slices from index 0 to index 5 but not including the element
_at index 5! This is the Python way, as you’ll see with other examples_
soon. |
It does take a little getting used to, but when you see this kind of
indexing at work elsewhere, you’ll understand the rationale.
What if we wanted the non-permanent members whose term ends in
2023? |
That’s Albania, Brazil, Gabon, Ghana, and UAE.
To get that slice we’d use
```
>>> un_security_council[5:10]
['Albania', 'Brazil', 'Gabon', 'Ghana', 'UAE']
```
Again, Python doesn’t return the item at index 10; it just goes up to
index 10 and stops.
###### Some shortcuts
Python allows a few shortcuts. |
For example, we can leave out the starting
index, and Python reads from the start of the list (or tuple).
```
>>> un_security_council[:10]
['China', 'France', 'Russia', 'UK', 'USA',
'Albania', 'Brazil', 'Gabon', 'Ghana', 'UAE']
```
By the same token, if we leave out the ending index, then Python will
read to th... |
You might
be able to step one stone at a time. You might be able to step two stones
at a time—skipping over every other stone. |
If you have long legs, or the
stones are very close together, you might be able to step three stones at
a time! |
We call this step size or stride.
In Python, when specifying slices we can specify the stride as a third
parameter. |
This comes in handy if we only want values at odd indices or
at even indices.
The syntax is <sequence>[<start>:<stop>:<stride>].
Here are some examples:
```
>>> un_security_council[::2] # only even indices
['China', 'Russia', 'USA', 'Brazil', 'Ghana',
'India', 'Kenya', 'Norway']
>>> un_security_council[1::2] #... |
Sure!
```
>>> un_security_council[-1::-1]
['Norway', 'Mexico', 'Kenya', 'Ireland', 'India',
'UAE', 'Ghana', 'Gabon', 'Brazil', 'Albania',
'USA', 'UK', 'Russia', 'France', 'China']
```
Now you know one way to get the reverse of a sequence. |
Can you think
of some use cases for changing the stride?
-----
###### 10.12 Passing mutables to functions
You’ll recall that as an argument is passed to a function it is assigned
to the corresponding formal parameter. |
This, combined with mutability,
can sometimes cause confusion.[7]
###### Mutable and immutable arguments to a function
Here’s an example where some confusion often arises.
```
>>> def foo(lst):
... |
lst.append('Waffles')
...
>>> breakfasts = ['Oatmeal', 'Eggs', 'Pancakes']
>>> foo(breakfasts)
>>> breakfasts
['Oatmeal', 'Eggs', 'Pancakes', 'Waffles']
```
Some interpret this behavior incorrectly, assuming that Python must
handle immutable and mutable arguments differently! |
This is not correct.
Python passes mutable and immutable arguments the same way. |
The
argument is assigned to the formal parameter.
The result of this example is only a little different than if we’d done
this:
```
>>> breakfasts = ['Oatmeal', 'Eggs', 'Pancakes']
>>> lst = breakfasts
>>> lst.append('Waffles')
>>> breakfasts
['Oatmeal', 'Eggs', 'Pancakes', 'Waffles']
```
All we’ve done is g... |
In the example with the function foo (above) the only difference is
that the name lst exists only within the scope of the function. |
Otherwise,
these two examples behave the same.
Notice that there is no “reference” being passed, just an assignment
taking place.
###### Names have scope, values do not
This example draws out another point. |
To quote Python guru Ned
Batchelder:
Names have scope but no type. |
Values have type but no scope.
7If you search on the internet you may find sources that say that immutable
object are passed by value and mutable objects are passed by reference in Python.
This is not correct! |
Python always passes by assignment—no exceptions. This is
different from many other languages (for example, C, C++, Java). |
If you haven’t
heard these terms before, just ignore them.
-----
What do we mean by that? |
Well, in the case where we pass the list
```
breakfast to the function foo, we create a new name for breakfast, lst.
```
This name, lst, exists only within the scope of the function, but the value
persists. |
Since we’ve given this list another name, breakfast, which exists
outside the scope of the function we can still access this list once the
function call has returned, even though the name lst no longer exists.
Here’s another demonstration which may help make this more clear.
```
>>> def foo(lst):
... |
lst.append('Waffles')
... |
print(lst)
...
>>> foo(['Oatmeal', 'Eggs', 'Pancakes'])
['Oatmeal', 'Eggs', 'Pancakes', 'Waffles']
```
However, now we can no longer use the name lst since it exists only
within the scope of the function.
```
>>> lst
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ... |
Did you mean: 'list'?
###### Where did the list go?
```
When an object no longer has a name that refers to it, Python will destroy
the object in a process called garbage collection. |
We won’t cover garbage
collection in detail. |
Let it suffice to understand that once an object no
longer has a name that refers to it, it will be subject to garbage collection,
and thus inaccessible.
So in the previous example, where we passed a list literal to the function, the only time the list had a name was during the execution of the
function. |
Again, the formal parameter is lst, and the argument (in this
last example) is the literal ['Oatmeal', 'Eggs', 'Pancakes']. |
The assignment that took place when the function was called was lst = ['Oatmeal',
```
'Eggs', 'Pancakes']. Then we appended 'Waffles', printed the list, and
```
returned.
Poof! |
lst is gone.
-----
###### 10.13 Exceptions
```
IndexError
```
When dealing with sequences, you may encounter IndexError. |
This exception is raised when an integer is supplied as an index, but there is no
element at that index.
```
>>> lst = ['j', 'a', 's', 'p', 'e', 'r']
>>> lst[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
```
Notice that the error message explic... |
There is no element at index six, so if we attempt to access
```
lst[6], an IndexError is raised.
TypeError
```
Again, when dealing with sequences, you may encounter TypeError in
a new context. |
This occurs if you try to use something other than an
integer (or slice) as an index.
```
>>> lst[1.0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not float
>>> lst['cheese']
Traceback (most recent call last):
File "<stdin>",... |
aardvark
b. bat
c. cheetah
d. dikdik
e. |
ermine
Give an example of an index, n, that would result in an IndexError if we
were to use it in the expression mammals[n].
**Exercise 02**
Given the following tuple
```
>>> elements = (None, 'hydrogen', 'helium', 'lithium',
... |
'beryllium', 'boron', 'carbon',
... 'nitrogen', 'oxygen')
```
write the indices that correspond to
a. beryllium
b. boron
c. carbon
d. helium
e. hydrogen
f. lithium
g. nitrogen
h. |
oxygen
(Extra: If you’ve had a course in chemistry, why do you think the first
element in the tuple is None?)
**Exercise 03**
Given the polynomial 4𝑥[3] +2𝑥[2] +5𝑥−4, write the coefficients as a tuple
and name the result coefficients. |
Use an assignment.
a. What is the value of len(coefficients)?
b. What is the value of coefficients[2]?
c. |
Did you write the coefficients in ascending or descending order?
Why did you make that choice?
-----
**Exercise 04**
Given the lists in exercises 1 and 2
```
>>> mammals = ['cheetah', 'aardvark', 'bat', 'dikdik', 'ermine']
>>> elements = (None, 'hydrogen', 'helium', 'lithium',
... |
'beryllium', 'boron', 'carbon',
... 'nitrogen', 'oxygen')
```
what is the evaluation of the following expressions?
a. len(mammals) > len(elements)
b. elements[5] < mammals[2]
c. |
elements[-1]
**Exercise 05**
Write a function which, given any arbitrary list, returns True if the list
has an even number of elements and False if the list has an odd number
of elements. |
Name your function is_even_length().
**Exercise 06**
Given the following list
```
moons = ['Mimas', 'Enceladus', 'Tethys', 'Dione']
```
write one line of code which calls the function is_even_length() (see
Exercise 05) with moons as an argument and assigns the result to an
object named n. |
What is n’s type?
**Exercise 07**
Given the following list, which contains data about some moons of Saturn
and their diameters (in km),
```
moons = [('Mimas', 396.4), ('Enceladus', 504.2),
('Tethys', 1062.2), ('Dione', 1122.8)]
```
a. |
If we were to perform the assignment m = moons[0], what would m’s
type be?
b. How would we get the name of the moon from m?
c. How would we get the diameter of the moon from m?
d. |
Write a single line of code which calculates the average diameter of these moons, and assigns the result to an object named
```
avg_diameter. (No, you do not need a loop.)
```
e. |
Write one line of code which adds Iapetus to the list, using the
same structure. The diameter of Iapetus is 1468.6 (km).
-----
f. |
In one line of code, write an expression which returns the diameter
of Enceladus, and assigns the result to an object named diameter.
g. |
What is the evaluation of the expression `moons[0][0]` `<`
```
moons[1][0]?
```
**Exercise 08**
Given the following
```
>>> countries = ['Ethiopia', 'Benin', 'Ghana', 'Angola',
... |
'Cameroon', 'Kenya']
>>> countries.append('Nigeria')
>>> countries.sort()
>>> countries.pop()
>>> country = countries[2]
```
answer the following questions:
a. |
What is the value of len(countries)?
b. What is the resulting value of country?
c. |
What is the evaluation of len(countries[3])
**Exercise 09**
There are three ways to make a copy of a list:
```
lst_2 = lst_1.copy() # using the copy() method
lst_2 = lst_1[:] # slice encompasses entire list
lst_2 = list(lst_1) # using the list() constructor
```
Write a function that takes a list as an argument... |
How you modify the
list is up to you, but you should use at least two different list methods.
Demonstrate that when you call this function with a list variable as
an argument, that the function returns a modified copy, and that the
original list is unchanged.
-----
-----
#### Chapter 11
### Loops and iteration
In... |
With loops, we can automate repetitive tasks or calculations. Why are they called loops? |
Well, so far we’ve
seen code which (apart from function calls) progresses in a linear fashion
from beginning to end (even if there are branches, we still proceed in a
linear fashion). |
Loops change the shape of the execution of our code in
a very interesting and powerful way. |
They loop!
Looping allows portions of our code to execute repeatedly—either for
a fixed number of times or while some condition holds—before moving
on to execute the rest of our code.
Python provides us with two types of loop: for loops and while loops.
```
for loops work by iterating over some iterable object, be it a... |
while loops continue as long as some condition
is true.
**Figure 11.1**
With variables, functions, branching, and loops, we have all the tools
we need to create powerful programs. |
All the rest, as they say, is gravy.
211
-----
**Learning objectives**
- You will learn how to use for loops and while loops.
- You will learn how to iterate over sequences.
- You will learn how to define and use conditions which govern a
```
while loop.
```
- You will learn how to choose which type ... |
Humans don’t much enjoy repetitive tasks. Computers couldn’t care less. |
They’re capable of performing
repetitive tasks with relative ease.
We perform repetitive tasks or calculations, or operations on elements
in some data structure using loops or iteration.
We have two basic types of loops in Python: while loops, and for
loops.
If you’ve written code in another language, you may find that... |
What is an iterable? An iterable
is a composite object (made of parts, called “members” or “elements”)
which is capable of returning its members one at a time, in a specific
sequence. |
Recall: lists, tuples, and strings are all iterable.
Take, for example, this list:
-----
```
m = [4, 2, 0, 1, 7, 9, 8, 3]
```
If we ask Python to iterate over this list, the list object itself “knows”
how to return a single member at a time: 4, then 2, then 0, then 1, etc.
We can use this to govern how many itera... |
For this we have the
```
while loop. |
A while loop continues to execute, as long as some condition
```
_is true or has a truthy value._
Imagine you’re simulating a game of blackjack, and it’s the dealer’s
turn. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.