0% found this document useful (0 votes)
51 views12 pages

Python Exception Handling and Lists

The document covers exception handling in Python, explaining how to manage errors to prevent program crashes. It also details lists, including their creation, indexing, slicing, and methods for adding, removing, and sorting items. Additionally, it discusses the differences between mutable lists and immutable tuples, as well as type conversion between lists and tuples.

Uploaded by

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

Python Exception Handling and Lists

The document covers exception handling in Python, explaining how to manage errors to prevent program crashes. It also details lists, including their creation, indexing, slicing, and methods for adding, removing, and sorting items. Additionally, it discusses the differences between mutable lists and immutable tuples, as well as type conversion between lists and tuples.

Uploaded by

inuman739
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

(Notes for II IA )

Exception Handling

An error is an exception in Python program means the entire program will crash. You
don’t want this to happen in real-world programs. Instead, you want the program to detect
errors, handle them, and then continue to run.

For example, consider the following program, which has a “divide-byzero” error.

a=int(input(‘Enter numerator’))
b=int(input(‘Enter denominator’))
try:
c=a/b
print(‘Division result=’, c)
exception:
print(‘Do not divide a number by zero’)

LISTS

A list is a value that contains multiple values in an ordered sequence. The term list value
refers to the list itself (which is a value that can be stored in a variable or passed to a function like
any other value), not the values inside the list value.

Examples of lists :
1. ['cat', 'bat', 'rat', 'elephant'].
2. [1, ‘hello’ , 20.5 , True, ‘h’ , None]

Values inside the list are also called items. Items are separated with commas (that is,
they are comma-delimited).

For example, enter the following into the interactive shell:


>>> [1, 2, 3]
[1, 2, 3]

>>> ['cat', 'bat', 'rat', 'elephant']


['cat', 'bat', 'rat', 'elephant']

>>> ['hello', 3.1415, True, None, 42]


['hello', 3.1415, True, None, 42]

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam
['cat', 'bat', 'rat', 'elephant']

>>>spam=[ ] # An empty list


Getting Individual Values in a List with Indexes
The integer inside the square brackets that follows the list is called an index. The first
value in the list is at index 0, the second value is at index 1, the third value is at index 2, and
so on.

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam[0]
'cat'

>>> spam[1]
'bat'

>>> spam[2]
'rat'

>>> spam[3]
'elephant'

spam = ["cat", "bat", "rat", "elephant"]


spam[0] spam[1] spam[2] spam[3]

>>> 'Hello ' + spam[0]


'Hello cat'

>>> spam[10000]
IndexError: list index out of range

>>> spam[1.0]
TypeError: list indices must be integers, not float

>>> spam[int(1.0)]
'bat'

Lists can also contain other list values. The values in these lists of lists can be accessed using
multiple indexes, like so:
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0]
['cat', 'bat']

>>> spam[0][1]
'bat'

>>> spam[1][4]
50
Negative Indexes
While indexes start at 0 and go up, you can also use negative integers for the index.
The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last
index in a list, and so on.

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam[-1]
'elephant'

>>> spam[-3]
'bat'

Getting Sublists with Slices


A slice can get several values from a list, in the form of a new list. A slice is typed
between square brackets, like an index, but it has two integers separated by a colon. between
indexes and slices.

spam[2] is a list with an index (one integer).

spam[1:4] is a list with a slice (two integers).

In a slice, the first integer is the index where the slice starts. The second integer is the index
where the slice ends. A slice goes up to, but will not include, the value at the second index. A
slice evaluates to a new list value.

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']

>>> spam[1:3]
['bat', 'rat']

>>> spam[0:-1]
['cat', 'bat', 'rat']

Leaving out the first index is the same as using 0,or the beginning of the list. Leaving out the
second index is the same as using the length of the list, which will slice to the end of the list.

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam[:2]
['cat', 'bat']

>>> spam[1:]
['bat', 'rat', 'elephant']

>>> spam[:]
['cat', 'bat', 'rat', 'elephant']

Getting a List’s Length with len()


The len() function will return the number of values that are in a list value passed to it,
just like it can count the number of characters in a string value.

>>> len(spam)
3

Changing Values in a List with Indexes


Use an index of a list to change the value at that index.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'ant'
>>> spam
['cat', 'ant', 'rat', 'elephant']

>>> spam[2] = spam[1]


>>> spam
['cat', 'ant', 'ant', 'elephant']

>>> spam[-1] = 12345


>>> spam
['cat', 'ant', 'ant', 12345]

List Concatenation and List Replication


The + operator can combine two lists to create a new list value in the same way it
combines two strings into a new string value. The * operator can also be used with a list and
an integer value to replicate the list.
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']

Removing Values from Lists with del Statements


The del statement will delete values at an index in a list. All of the values in the list
after the deleted value will be moved up one index.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']

in and not in Operators


You can determine whether a value is or isn’t in a list with the in and not in operators.
Like other operators, in and not in are used in expressions and connect two values: a value to
look for in a list and the list where it may be found. These expressions will evaluate to a
Boolean value.

>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']


True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True

For example, the following program lets the user type in a pet name
and then checks to see whether the name is in a list of pets.

myPets = ['Zophie', 'Pooka', 'Fat-tail']


print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')

Methods
A method is the same thing as a function, except it is “called on” a value.

Finding a Value in a List with the index() Method


List values have an index() method that can be passed a value, and if that value exists
in the list, the index of the value is returned. If the value isn’t in the list, then Python produces
a Value Error error.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> [Link]('hello')
0
>>> [Link]('heyas')
3
>>> [Link]('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list

When there are duplicates of the value in the list, the index of its first appearance is returned.
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> [Link]('Pooka')
1
Adding Values to Lists with the append() and insert() Methods
To add new values to a list, use the append() and insert() methods.

>>> spam = ['cat', 'dog', 'bat']


>>> [Link]('moose')

>>> spam
['cat', 'dog', 'bat', 'moose']

The previous append() method call adds the argument to the end of the list.

The insert() method can insert a value at any index in the list.
The first argument to insert() is the index for the new value, and the second argument is the
new value to be inserted.

>>> spam = ['cat', 'dog', 'bat']


>>> spam. insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']

NOTE:Methods belong to a single data type. The append() and insert() methods are list
methods and can be called only on list values, not on other values
such as strings or integers

>>> eggs = 'hello'


>>> [Link]('world')
AttributeError: 'str' object has no attribute 'append'
>>> bacon = 42
>>> [Link](1, 'world')
AttributeError: 'int' object has no attribute 'insert'

Removing Values from Lists with remove()


The remove() method is passed the value to be removed from the list it is called on.
Enter the following into the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> [Link]('bat')
>>> spam
['cat', 'rat', 'elephant']

Attempting to delete a value that does not exist in the list will result in a ValueError
error. For example, enter the following into the interactive shell
and notice the error that is displayed:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> [Link]('chicken')
ValueError: [Link](x): x not in list

If the value appears multiple times in the list, only the first instance of
the value will be removed. Enter the following into the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
>>> [Link]('cat')
>>> spam
['bat', 'rat', 'cat', 'hat', 'cat']

The del is good to use when you know the index of the value you want to remove from
the list. The remove() method is good when you know the value you want to remove from the
list.

Sorting the Values in a List with the sort() Method


Lists of number values or lists of strings can be sorted with the sort()
method.
>>> spam = [2, 5, 3.14, 1, -7]
>>> [Link]()
>>> spam
[-7, 1, 2, 3.14, 5]

>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']


>>> [Link]()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']

You can also pass True for the reverse keyword argument to have sort()
sort the values in reverse order.
>>> [Link](reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']

There are three things you should note about the sort() method.

1. First, the sort() method sorts the list in place; don’t try to capture the return value by
writing code like
spam = [Link](). #invalid

2. Second, you cannot sort lists that have both number values and string values in them,
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> [Link]() #invalid

[Link], sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting
strings. This means uppercase letters come before lowercaseletters. Therefore, the lowercase
a is sorted so that it comes after the uppercase Z.

>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']


>>> [Link]()
>>> spam
['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
List-like Types: Strings and Tuples
Strings and lists are actually similar, if you consider a string to be a “list” of single text
characters. Many of the things you can do with lists can also be done with strings: indexing;
slicing; and using them with for loops, with len(), and with the in and not in operators.

>>> name = 'Zophie'


>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False

Mutable and Immutable Data Types


A list value is a mutable data type: It can have values added, removed, or changed.
However, a string is immutable: It cannot be changed. Trying to reassign a single character in
a string results in a TypeError

>>> name = 'Zophie a cat'


>>> name[7] = 'the'
TypeError: 'str' object does not support item assignment

Strings are immutable.


List value is mutable.
does not modify the list eggs:
>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[4, 5, 6]

The Tuple Data Type


The tuple data type is almost identical to the list data type, except in two ways. First,
tuples are typed with parentheses, ( and ), instead of square brackets, [ and ]. For example,
enter the following into the interactive shell:
>>> eggs = ('hello', 42, 0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
3
The main way that tuples are different from lists is that tuples, like strings, are immutable.
Tuples cannot have their values modified,appended, or removed.
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
TypeError

If there is only one value in a tuple, you can indicate this by placing a trailing comma
after the value inside the parentheses. Otherwise, Python will think you’ve just typed a value
inside regular parentheses. The comma is what lets Python know this is a tuple value. (Unlike
some other programming languages,

>>> spam=(‘hello’)
>>>type(spam)
<class 'str'>
>>>spam =(‘hello’,)
>>> type(spam)
<class 'tuple'>

Advantages of tuples
 If one need an ordered sequence of values that never changes, use a tuple.
 because they are immutable
 Python can implement some optimizations that make code using tuples slightly faster
than code using lists.

Converting Types with the list() and tuple() Functions


The functions list() and tuple() will return list and tuple versions of the values passed
to them.

>>> tuple(['cat', 'dog', 5])


('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Converting a tuple to a list is handy if you need a mutable version of a tuple value.

References
Variables store strings and integer values.
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
. A reference is a value that points to some bit of data, and a list reference is a value that
points to a list.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
>>> cheese[1] = 'Hello!'
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese
[0, 'Hello!', 2, 3, 4, 5]

When list is created, a reference is passed to it in the spam variable. This means the values
stored in spam and cheese now both refer to the same list.. So when we modify the first
element of cheese , we are modifying the same list that spam refers to.

Dictionary Data Type

A dictionary is a collection of many values. But unlike indexes for lists, indexes for
dictionaries can use many different data types, not just integers. Indexes for dictionaries are
called keys, and a key with its associated value is called a key-value pair.
In code, a dictionary is typed with braces, {}.

>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud


This assigns a dictionary to the myCat variable.
This dictionary’s keys are 'size', 'color', and 'disposition'.
The values for these keys are 'fat', 'gray', and 'loud', respectively.

>>> myCat['size']
'fat'
>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'

Dictionaries vs. Lists


Lists are ordered sequence of values wheas iems in dictionaries are unordered.
The first item in a list named spam would be spam[0]. But there is no “first” item in a
dictionary.

>>> spam = ['cats', 'dogs', 'moose']


>>> bacon = ['dogs', 'moose', 'cats']
>>> spam == bacon
False
>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
True
>>> spam['color']
KeyError: 'color'
The keys(), values(), and items() Methods

There are three dictionary methods that will return list-like values of the
dictionary’s keys, values, or both keys and values: keys(), values(), and items().

Note:The values returned by these methods (dict_keys,dict_values, and dict_items, are


not true lists: They cannot be modified and do not have an append() method. But these
data types (dict_keys,dict_values, and dict_items, respectively) can be used in for loops.

If you want a true list from one of these methods, pass its list-like return value to the list()
function.

keys()method returns a list with the keys of the dictionary.

>>> spam = {'color': 'red', 'age': 42}


>>> [Link]()
dict_keys(['color', 'age'])
>>> list([Link]())
['color', 'age']

The list([Link]()) line takes the dict_keys value returned from keys() and passes it to
list(), which then returns a list value of ['color', 'age'].

values()method returns a list with the values of the dictionary.

>>> spam = {'color': 'red', 'age': 42}


>>> [Link]()
dict_values(['red’, 42])
>>> list([Link]())
['red', 42]

items()method returns a list with the items of the dictionary.

>>> spam = {'color': 'red', 'age': 42}


>>> [Link]()
dict_items ([(‘color’, red),(‘age’,42)])
>>> list(spam. items())
[(‘color’, 'red'),(‘age’, 42)]

Checking Whether a Key or Value Exists in a Dictionary


in (or not in)operator is used to check a particular values exists as a key or a values in a
dictionary.
>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in [Link]()
True
>>> 'Zophie' in [Link]()
True
>>> 'color' in [Link]()
False
>>> 'color' not in [Link]()
True
>>> 'color' in spam
False

get() Method
Dictionaries have a get() method that takes two arguments: the key of the value to
retrieve and a fallback value to return if that key does not exist.

>>> picnicItems = {'apples': 5, 'cups': 2}


>>> 'I am bringing ' + str([Link]('cups', 0)) + ' cups.'
'I am bringing 2 cups.'

>>> 'I am bringing ' + str([Link]('eggs', 0)) + ' eggs.'


'I am bringing 0 eggs.'
Because there is no 'eggs' key in the picnicItems dictionary, the default value 0 is returned by
the get() method. Without using get(), the code would have caused an error message, such as
in the following example:

>>> picnicItems = {'apples': 5, 'cups': 2}


>>> 'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
KeyError: 'eggs'

setdefault() Method

If a key does not already have a value, a code b elike this:

spam = {'name': 'Pooka', 'age': 5}


if 'color' not in spam:
spam['color'] = 'black'

setdefault() method offers a way to do this in one line of code. The first argument passed to
the method is the key to check for, and the second argument is the value to set at that key if
the key does not exist.
:
>>> spam = {'name': 'Pooka', 'age': 5}
>>> [Link]('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
The setdefault() method is a nice shortcut to ensure that a key exists.

You might also like