Python Questions
Python Questions
UNIT-1
Hour-1 Topic: Variables, expressions, and statements: Values and types, Variables, Variable
names and keywords, Statements, Operators and operands, Expressions, Order of operations,
Modulus operator, String operations, Asking the user for input, Comments, choosing mnemonic
variable names, Debugging,
Value:
If you want to know what type value a variable contains then use type method
>>>type('BMSCE')
<class 'str'>
>>> type(10)
<class 'int'>
>>> type(3.2)
<class 'float'>
>>> type('17')
<class 'str'>
>>> type('3.2')
<class 'str'>
Variable:
One of the most powerful features of a programming language is the ability to manipulate variables. A
variable is a name that refers to a value.
1
PYTHON PROGRAMMING
This example makes three assignments. The first assigns a string to a new variable named message; the
second assigns the integer 17 to n; the third assigns the (approximate) value of to pi.
>>> print(n)
17
>>> print(pi)
3.141592653589793
76trombones is illegal because it begins with a number. more@ is illegal because it contains an illegal
character and class is a reserved keyword, they cannot be used as variable names
Statements:
A statement is a unit of code that the Python interpreter can execute. A script usually contains a sequence
of statements
2
PYTHON PROGRAMMING
Example:
print(1)
x=2
print(x)
Output:
1
2
>>> minute = 59
>>> minute/60
0.9833333333333333
As you see the above statement, the result of this division is a floating point result.
To obtain the integer answer use floored ( // integer) division.
>>> minute = 59
>>> minute//60
0
Expressions:
An expression is a combination of values, variables, and operators.
If you type an expression in interactive mode, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
Exercise 1: Type the following statements in the Python interpreter to see what they do:
100
a=100
3
PYTHON PROGRAMMING
b=200
a+b
Order of operations:
When more than one operator appears in an expression, the order of evaluation depends on the rules of
precedence.
For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful
way to remember the rules:
● Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want.
Example: 2 * (3-1) is 4, and (1+1)**(5-2) is 8.
● Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27.
● Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
● Operators with the same precedence are evaluated from left to right. So the expression 5-3-1 is
1, not 3, because the 5-3 happens first and then 1 is subtracted from 2.
Modulus operator:
The modulus operator works on integers and yields the remainder when the first operand is divided by
the second. In Python, the modulus operator is a percent sign (%).
>>> quotient = 7 // 3
>>> print(quotient)
2
>>> remainder = 7 % 3
>>> print(remainder)
1
String operations:
The + operator works with strings, but it is not an addition in the mathematical sense. Instead it performs
concatenation, which means joining the strings by linking them end to end.
For example:
>>> first = 10
>>> second = 15
>>> print(first+second)
25
>>> first = '100'
>>> second = '150'
>>> print(first + second)
100150
4
PYTHON PROGRAMMING
The * operator also works with strings by multiplying the content of a string by an integer.
For example:
>>> first = 'Test '
>>> second = 3
>>> print(first * second)
Test Test Test
If you expect the user to type an integer, you can try to convert the return value to int using the int()
function:
Comments:
In Python comments start with the # symbol
Even we can write comments after the valid statement as given below:
5
PYTHON PROGRAMMING
Everything from the # to the end of the line is ignored; it has no effect on the program.
Exercise:
The following examples use the operator ==, which compares two operands and produces True if they
are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the class bool; they are not strings:
>>> type(True)
6
PYTHON PROGRAMMING
<class 'bool'>
>>> type(False)
<class 'bool'>
Logical operators:
There are three logical operators: and, or, and not.
Operator Meaning
or Short circuit OR
For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.
n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or
3.
7
PYTHON PROGRAMMING
Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false; that is, if x
is less than or equal to y.
Conditional Execution:
We need the ability to check conditions and change the behavior of the program accordingly.
Conditional statements give us this ability.
The simplest form is the if statement:
If condition1:
statements
For Example:
if x > 0 :
print('x is positive')
The boolean expression after the if statement is called the condition. We end the if statement with a colon character
(:) and the lines after the if statement are indented.
In Fig 1, If the logical condition is true, then the indented statement gets executed. If the logical condition is false,
the indented statement is skipped.
There is no limit on the number of statements that can appear in the body, but there must be at least one. In few
scenario, where there is no statement that appear in the body then we can use pass statement
if x < 0 :
pass # need to handle negative values but currently no statement is present then use pass
8
PYTHON PROGRAMMING
Another scenario is
if <expr>:
<statement>
<statement>
...
<statement>
<following_statement>
In the above syntax, all the statements at the matching indentation level are considered part of the same block.
Either way <following statement> will follow execution after if statement completes its execution.
x=11
if x>10:
print('Expression was true')
print('Executing statement in suite')
print('...')
print('Done.')
print('After conditional')
Output:
Expression was true
Executing statement in suite
…
Done
After Conditional
Alternative execution:
A second form of the if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed.
9
PYTHON PROGRAMMING
For Example:
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a
message to that effect. If the condition is false, the second set of statements is executed.
Chained conditionals:
Sometimes there are more than two possibilities and we need more than two branches. One way to express
a computation like that is a chained conditional:
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
10
PYTHON PROGRAMMING
elif is an abbreviation of "else if.". In the above changed conditionals exactly only one statement will be
executed. There is no limit on the number of elif statements. If there is an else clause, it has to be at the
end.
if choice == 'a':
print('Bad guess')
elif choice == 'b':
print('Good guess')
elif choice == 'c':
print('Close, but not correct')
Exercise:
1. Write a python program to check whether you are eligible to vote or not? Your program should
get the age of the voter from the user and if their age is 18 and above, let them vote otherwise
deny them from voting.
2. Write a python program that will check for the following conditions:
a. If the light is green – Car is allowed to go
b. If the light is yellow – Car has to wait
c. If the light is red – Car has to stop
d. Other signal – unrecognized signal. Example black, blue, etc…
3. Write a program to check students’ grades. Your program should fulfill the following conditions:
a. Grade A – Outstanding
b. Grade B – Excellent
c. Grade C – Very Good
d. Grade D – Good
e. Grade E – Satisfactory
f. Grade F– UnSatisfactory
A program should also ask to enter the student’s name, class, and section.
11
PYTHON PROGRAMMING
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
The outer conditional contains two branches. The first branch contains a simple statement. The second
branch contains another if statement, which has two branches of its own. Those two branches are both
simple statements, although they could have been conditional statements as well.
Exercise:
1. Modify the earlier program (3rd Program) students’ grades in such a way that they should take
in five subject marks. Find the total mark and their percentage. Your program should check for
the following conditions:
a. If the percentage falls below 40, they are considered fail.
b. If the percentage is between 40 and 60, grade them as pass.
c. If the percentage is between 60 and 75, grade them as good.
d. If the percentage is between 75 and 85, grade them as very good.
e. If the percentage is between 85 and 100, grade them excellent.
f. If the percentage is below zero or above 100, it’s an error.
12
PYTHON PROGRAMMING
Hour-4 Topic: Catching exceptions using try and except, Short-circuit evaluation of logical
expressions
Iteration: Updating variables, the while statement, Infinite loops, break, finishing iterations with
continue
to a Celsius temperature
If we execute this code and give it invalid input, it simply fails with an unfriendly error message:
python fahren.py
python fahren.py
There is a conditional execution structure built into Python to handle these types of expected and
unexpected errors called “try / except”.
The idea of try and except is that you know that some sequence of instructions may have a problem and
you want to add some statements to be executed if an error occurs. These extra statements (the except
block) are ignored if there is no error.
13
PYTHON PROGRAMMING
Python starts by executing the sequence of statements in the try block. If all goes well, it skips the except
block and proceeds.
If an exception occurs in the try block, Python jumps out of the try block and executes the sequence of
statements in the except block.
python fahren2.py
Enter Fahrenheit Temperature:72
22.22222222222222
python fahren2.py
Enter Fahrenheit Temperature: Fred
Please enter a number
Because of the definition of and, if x is less than 2, the expression x >= 2 is False and so the whole
expression is False regardless of whether (x/y) > 2 evaluates to True or False.
When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it
stops its evaluation and does not do the computations in the rest of the logical expression. When the
evaluation of a logical expression stops because the overall value is already known, it is called short-
circuiting the evaluation.
14
PYTHON PROGRAMMING
The third calculation failed because Python was evaluating (x/y) and y was zero, which causes a runtime
error. But the first and the second examples did not fail because in the first calculation y was non zero
and in the second one the first part of these expressions x >= 2 evaluated to False so the (x/y) was not
ever executed due to the short-circuit rule and there was no error.
Iteration: Iteration means executing the similar block of code over and over, that’s many times. A
programming structure that implements iteration is called a loop.
Updating variables:
Case 1:
x=x+2 # Assignment with expression
print(x) #printing the updated value of x
Case 2:
x=2 # variable x is assigned value 2
x=x+2 # Assignment with expression
print(x) #printing the updated value of x
Case 1 will generate error as variable x is not defined, but case 2 will execute as variable x is assigned
value 2
While Loop:
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without
making errors is something that computers do well and people do poorly. Because iteration is so common,
Python provides several language features to make it easier
15
PYTHON PROGRAMMING
One form of iteration in Python is the while statement. Here is a simple program that counts down from
five and then says “Hurray!”.
n=5
while n > 0:
print(n)
n=n-1
print(Hurray!')
while <expr>:
<statement(s)>
Infinite loops:
Suppose you write a while loop that theoretically never ends
16
PYTHON PROGRAMMING
An endless source of amusement for programmers is the observation that the directions on shampoo,
“Lather, rinse, repeat,” are an infinite loop because there is no iteration variable telling you how many
times to execute the loop.
n = 10
while True:
print(n, end=' ')
n=n-1
print('Done!')
While this is a dysfunctional infinite loop, we can still use this pattern to build useful loops as long as we
carefully add code to the body of the loop to explicitly exit the loop using break when we have reached
the exit condition.
For example, suppose you want to take input from the user until they type done. You could write:
while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done!')
it prompts the user with an angle bracket. If the user types done, the break statement exits the loop.
Otherwise the program echoes whatever the user types and goes back to the top of the loop.
Output:
> hello there
hello there
> finished
finished
> done
Done!
17
PYTHON PROGRAMMING
while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done!')
Here is an example of a loop that copies its input until the user types “done”, but treats lines that start
with the hash character as lines not to be printed (kind of like Python comments).
Output:
> hello there
hello there
>#
> print this!
print this!
> done
done!
Exercise:
1. Write a program to print n natural number in descending order using a while loop
2. Write a program to find greatest common divisor (GCD) or highest common factor (HCF) of two
numbers.
3. Factorial of any number n is represented by n! and is equal to 1*2*3*. .. *(n-1)*n.
E.g.- 4! = 1*2*3*4 = 24
3! = 3*2*1 = 6
2! = 2*1 = 2
Also,
1! = 1
0! = 1
Write a program to calculate the factorial of a number.
Hour-5 Topic: Definite loops using for, Loop patterns, Counting and summing loops, Maximum
and minimum loops
18
PYTHON PROGRAMMING
Here, this type of loop iterates over a collection of objects, rather than specifying numeric values or
conditions:
We call the while statement an indefinite loop because it simply loops until some condition becomes
False, whereas the for loop is looping through a known set of items so it runs through as many iterations
as there are items in the set.
Output:
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
Loop patterns:
19
PYTHON PROGRAMMING
count = 0
for itervar in [3, 41, 12, 9, 74, 15]:
count = count + 1
print('Count: ', count)
We set the variable count to zero before the loop starts, then we write a for loop to run through the list of
numbers. Our iteration variable is named itervar and while we do not use itervar in the loop, it does
control the loop and cause the loop body to be executed once for each of the values in the list. In the body
of the loop, we add 1 to the current value of count for each of the values in the list. While the loop is
executing, the value of count is the number of values we have seen. Once the loop completes, the value
of count is the total number of items.
Output:
Count: 6
Another Example:
total = 0
for itervar in [3, 41, 12, 9, 74, 15]:
total = total + itervar
print('Total: ', total)
Output:
Total: 154
To find the largest value in a list or sequence, we construct the following loop:
largest = None
print('Before:', largest)
for itervar in [3, 41, 12, 9, 74, 15]:
if largest is None or itervar > largest :
largest = itervar
print('Loop:', itervar, largest)
print('Largest:', largest)
20
PYTHON PROGRAMMING
Loop: 9 41
Loop: 74 74
Loop: 15 74
Largest: 74
The variable largest is best thought of as the “largest value we have seen so far”. Before the loop, we set
largest to the constant None. None is a special constant value which we can store in a variable to mark
the variable as “empty”.
While the loop is executing, if largest is None then we take the first value we see as the largest so far.
You can see in the first iteration when the value of itervar is 3, since largest is None, we immediately set
largest to be 3.
To compute the smallest number, the code is very similar with one small change:
smallest = None
print('Before:', smallest)
for itervar in [3, 41, 12, 9, 74, 15]:
if smallest is None or itervar < smallest:
smallest = itervar
print('Loop:', itervar, smallest)
print('Smallest:', smallest)
Again, smallest is the “smallest so far” before, during, and after the loop executes. smallest contains the
minimum value in the list
For Example:
# printing first 6
# whole number
for i in range(6):
21
PYTHON PROGRAMMING
Output: 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Output: 0 2 4 6 8
In the above example, we are printing even numbers between 0 and 10, so we choose our starting point
from 0 (start=0) and stop the series at 10 (stop=10).
For printing an even number the difference between one number and the next must be 2 (step=2) after
providing a step we get the following output (0, 2, 4, 8).
Exercise:
1. Write a Python program to print all the even numbers within the given range.
2. Write a Python program to calculate the sum of all numbers from 1 to a given number
3. Write a Python program to calculate the sum of all the odd numbers within the given range
4. Write a Python program to count the total number of digits in a number.
22
PYTHON PROGRAMMING
UNIT-2
Hour-1 Topic: A string is a sequence, Getting the length of a string using len, Traversal through a
string with a loop, String slices
Overview:A string is a sequence of characters. You can access the characters one at a time with the
bracket operator:
Application:
The expression in brackets is called an index. The index indicates which character in the sequence you
want (hence the name). But you might not get what you expect:
>>> print(letter)
a
For most people, the first letter of “banana” is “b”, not “a”. But in Python, the index is an offset from
the beginning of the string, and the offset of the first letter is zero.
>>> letter = fruit[0]
>>> print(letter)
b
So “b” is the 0th letter (“zero-th”) of “banana”, “a” is the 1th letter (“one-th”), and “n” is the 2th (“two-
th”) letter.
You can use any expression, including variables and operators, as an index, but the value of the index
has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers
23
PYTHON PROGRAMMING
To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit) >>> last = fruit[length]
IndexError: string index out of range The reason for the IndexError is that there is no letter in “banana”
with the index 6.
Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have
to subtract 1 from length:
>>> last = fruit[length-1]
>>> print(last)
a
Alternatively, you can use negative indices, which count backward from the end of the string. The
expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
A lot of computations involve processing a string one character at a time. Often they start at the beginning,
select each character in turn, do something to it, and continue until the end. This pattern of processing is
called a traversal. One way to write a traversal is with a while loop:
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
Each time through the loop, the next character in the string is assigned to the variable char. The loop
continues until no characters are left.
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
24
PYTHON PROGRAMMING
Exercises: Exercise 1: Write a while loop that starts at the last character in the string and works its way
backwards to the first character in the string, printing each letter on a separate line, except backwards.
2. Given that fruit is a string, what does fruit[:] mean?
3. Take the following Python code that stores a string: str = 'X-DSPAM-Confidence:0.8475' Use find
and string slicing to extract the portion of the string after the colon character and then use the float
function to convert the extracted string into a floating point number.
4. Write a Python program to calculate the length of a string.
Hour-2 Topic: Strings are immutable, Looping and counting, The in operator, String comparison
Overview: It is tempting to use the operator on the left side of an assignment, with the intention of
changing a character in a string.
For example:
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
The “object” in this case is the string and the “item” is the character you tried to assign. For now, an
object is the same thing as a value, but we will refine that definition later. An item is one of the values in
a sequence. The reason for the error is that strings are immutable, which means you can’t change an
existing string. The best you can do is create a new string that is a variation on the original:
This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string.
The following program counts the number of times the letter “a” appears in a string:
word = 'banana'
25
PYTHON PROGRAMMING
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
This program demonstrates another pattern of computation called a counter. The variable count is
initialized to 0 and then incremented each time an “a” is found. When the loop exits, count contains the
result: the total number of a’s.
The in operator
The word in is a boolean operator that takes two strings and returns True if the first appears as a substring
in the second:
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
String comparison
The comparison operators work on strings. To see if two strings are equal:
if word == 'banana':
print('All right, bananas.')
Other comparison operations are useful for putting words in alphabetical order:
if word < 'banana':
print('Your word,' + word + ', comes before banana.')
elif word > 'banana':
print('Your word,' + word + ', comes after banana.')
else:
print('All right, bananas.')
Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase
letters come before all the lowercase letters, so: Your word, Pineapple, comes before banana. A common
way to address this problem is to convert strings to a standard format, such as all lowercase, before
performing the comparison. Keep that in mind in case you have to defend yourself against a man armed
with a Pineapple.
Exercises:
1. Write a program that accepts a string from user. Your program should count and display number
of vowels in that string.
2. Write a Python program to compare two strings and if the strings are equal, True should be
printed or else False should be printed.
26
PYTHON PROGRAMMING
3. Write a Python program to iterate through a string and check whether a particular character is
present or not. If present, true should be printed otherwise, false should be printed.
Overview: Strings are an example of Python objects. An object contains both data (the actual string itself)
and methods, which are effectively functions that are built into the object and are available to any instance
of the object. Python has a function called dir which lists the methods available for an object. The type
function shows the type of an object and the dir function shows the available methods.
Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case.
Calling a method is similar to calling a function (it takes arguments and returns a value) but the syntax is
different. We call a method by appending the method name to the variable name using the period as a
delimiter. For example, the method upper takes a string and returns a new string with all uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper().
>>> word = 'banana'
>>> new_word = word.upper()
>>> print(new_word)
BANANA
One common task is to remove white space (spaces, tabs, or newlines) from the beginning and end of a
string using the strip method:
>>> line = ' Here we go '
>>> line.strip()
27
PYTHON PROGRAMMING
'Here we go'
Some methods such as startswith return boolean values.
>>> line = 'Have a nice day'
>>> line.startswith('Have')
True
Parsing Strings
Often, we want to look into a string and find a substring. For example, if we were presented a series of
lines formatted as follows:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
and we wanted to pull out only the second half of the address (i.e., uct.ac.za) from each line, we can do
this by using the find method and string slicing.
First, we will find the position of the at-sign in the string. Then we will find the position of the first space
after the at-sign. And then we will use string slicing to extract the portion of the string which we are
looking for.
>>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
>>> atpos = data.find('@')
>>> print(atpos) 21
>>> sppos = data.find(' ',atpos)
>>> print(sppos) 31
>>> host = data[atpos+1:sppos]
>>> print(host) uct.ac.za
>>>
We use a version of the find method which allows us to specify a position in the string where we want
find to start looking. When we slice, we extract the characters from “one beyond the at-sign through up
to but not including the space character”.
Format Strings
The format operator, % allows us to construct strings, replacing parts of the strings with the data stored
in variables. When applied to integers, % is the modulus operator. But when the first operand is a string,
% is the format operator. The first operand is the format string, which contains one or more format
sequences that specify how the second operand is formatted. The result is a string.
For example, the format sequence %d means that the second operand should be formatted as an integer
(“d” stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string ‘42’, which is not to be confused with the integer value 42.
28
PYTHON PROGRAMMING
A format sequence can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
If there is more than one format sequence in the string, the second argument has to be a tuple1 . Each
format sequence is matched with an element of the tuple, in order. The following example uses %d to
format an integer, %g to format a floating-point number (don’t ask why), and %s to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple must match the number of format sequences in the string. The types
of the elements also must match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str
In the first example, there aren’t enough elements; in the second, the element is the wrong type
Exercises:
1. Write a program in Python to convert a word from lower case to upper case and display the
number of letters in that word.
2. Write a python program to find whether ‘w’ is present in the text “Hello world” using find method
and print the index of the letter ‘w’.
3. Write a program in Python to remove a newline in Python.
Hour-4 Topic: A list is a sequence, Lists are mutable, Traversing a list, List operations, List slices
Overview:
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any
type. The values in list are called elements or sometimes items.
Generic list examples
>>>list = [ 1 , 2 , 3 , 4 , 5 ]
>>>print list [1 , 2, 3, 4, 5]
>>>print list [0] #p r in t the l i s t item at index 0 1
>>>list.pop ( ) #remove and print the last item
There are several ways to create a new list; the simplest is to enclose the elements in square brackets (“["
and “]”):
29
PYTHON PROGRAMMING
A list within another list is nested. A list that contains no elements is called an empty list; you can create
one with empty brackets, []. As you might expect, you can assign list values to variables:
The syntax for accessing the elements of a list is the same as for accessing the characters of a string: the
bracket operator.
The expression inside the brackets specifies the index.
Remember that the indices start at 0:
>>> print(cheeses[0])
Cheddar
Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in
a list. When the bracket operator appears on the left side of an assignment, it identifies the element of the
list that will be assigned.
The one-th element of numbers, which used to be 123, is now 5. You can think of a list as a relationship
between indices and elements. This relationship is called a mapping; each index “maps to” one of the
elements. List indices work the same way as string indices: • Any integer expression can be used as an
index. • If you try to read or write an element that does not exist, you get an IndexError. • If an index has
a negative value, it counts backward from the end of the list. The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
30
PYTHON PROGRAMMING
Traversing a list
The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for
strings:
for cheese in cheeses:
print(cheese)
This works well if you only need to read the elements of the list. But if you want to write or update the
elements, you need the indices. A common way to do that is to combine the functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of elements in the list. range
returns a list of indices from 0 to n − 1, where n is the length of the list. Each time through the loop, i
gets the index of the next element. The assignment statement in the body uses i to read the old value of
the element and to assign the new value.
for x in empty:
print('This never happens.')
Although a list can contain another list, the nested list still counts as a single element. The length of this
list is four:
List operations
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
31
PYTHON PROGRAMMING
List Slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the
end. So if you omit both, the slice is a copy of the whole list.
>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle,
or mutilate lists. A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print(t) ['a', 'x', 'y', 'd', 'e', 'f']
Exercises:
Hour-5 Topic: List methods, Deleting elements, Lists and functions, Lists and strings, Parsing lines,
Objects and values, Aliasing, List arguments,
Overview: Python provides methods that operate on lists. For example, append adds a new element to
the end of a list.
extend takes a list as an argument and appends all of the elements:
sort arranges the elements of the list from low to high:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print(t) ['a', 'b', 'c', 'd']
32
PYTHON PROGRAMMING
There are several ways to delete elements from a list. If you know the index of the element you want,
you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t) ['a', 'c']
>>> print(x)
b
pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes
and returns the last element. If you don’t need the removed value, you can use the del statement:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print(t)
['a', 'c']
If you know the element you want to remove (but not the index), you can use remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print(t) ['a', 'c']
The return value from remove is None. To remove more than one element, you can use del with a slice
index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
['a', 'f']
As usual, the slice selects all the elements up to, but not including, the second index.
There are a number of built-in functions that can be used on lists that allow you to quickly look through
a list without writing your own loops:
>>> nums = [3, 41, 12, 9, 74, 15]
>>> print(len(nums))
6
33
PYTHON PROGRAMMING
>>> print(max(nums))
74
>>> print(min(nums))
3
>>> print(sum(nums))
154
>>> print(sum(nums)/len(nums))
25
The sum() function only works when the list elements are numbers. The other functions (max(), len(),
etc.) work with lists of strings and other types that can be comparable. We could rewrite an earlier
program that computed the average of a list of numbers entered by the user using a list.
In this program, we have count and total variables to keep the number and running total of the user’s
numbers as we repeatedly prompt the user for a number. We could simply remember each number as the
user entered it and use built-in functions to compute the sum and count at the end.
numlist = list()
while (True):
inp = input('Enter a number: ')
if inp == 'done': break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print('Average:', average)
We make an empty list before the loop starts, and then each time we have a number, we append it to the
list. At the end of the program, we simply compute the sum of the numbers in the list and divide it by the
count of the numbers in the list to come up with the average.
A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the
34
PYTHON PROGRAMMING
same as a string. To convert from a string to a list of characters, you can use list:
>>> s = 'spam'
>>> t = list(s)
>>> print(t)
['s', 'p', 'a', 'm']
Because list is the name of a built-in function, you should avoid using it as a variable name. I also avoid
the letter “l” because it looks too much like the number “1”. So that’s why I use “t”. The list function
breaks a string into individual letters. If you want to break a string into words, you can use the split
method:
Once you have used split to break the string into a list of words, you can use the index operator (square
bracket) to look at a particular word in the list. You can call split with an optional argument called a
delimiter that specifies which characters to use as word boundaries. The following example uses a hyphen
as a delimiter:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method,
so you have to invoke it on the delimiter and pass the list as a parameter:
In this case the delimiter is a space character, so join puts a space between words. To concatenate strings
without spaces, you can use the empty string, “”, as a delimiter.
Parsing lines Usually when we are reading a file we want to do something to the lines other than just
printing the whole line. Often we want to find the “interesting lines” and then parse the line to find some
interesting part of the line. What if we wanted to print out the day of the week from those lines that start
with “From”?
35
PYTHON PROGRAMMING
The split method is very effective when faced with this kind of problem. We can write a small program
that looks for lines where the line starts with “From”, split those lines, and then print out the third word
in the line:
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From '):
continue words = line.split()
print(words[2])
Sat
Fri
Fri
Fri
...
If we execute these assignment statements: a = 'banana' b = 'banana' we know that a and b both refer to a
string, but we don’t know whether they refer to the same string. There are two possible states:
In one case, a and b refer to two different objects that have the same value. In the second case, they refer
to the same object. To check whether two variables refer to the same object, you can use the is operator.
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
In this example, Python only created one string object, and both a and b refer to it. But when you create
two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
36
PYTHON PROGRAMMING
False
In this case we would say that the two lists are equivalent, because they have the same elements, but not
identical, because they are not the same object. If two objects are identical, they are also equivalent, but
if they are equivalent, they are not necessarily identical. Until now, we have been using “object” and
“value” interchangeably, but it is more precise to say that an object has a value. If you execute a = [1,2,3],
a refers to a list object whose value is a particular sequence of elements. If another list has the same
elements, we would say it has the same value.
Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object: >>> a = [1, 2,
3]
>>> b = a
>>> b is a
True
The association of a variable with an object is called a reference. In this example, there are two references
to the same object. An object with more than one reference has more than one name, so we say that the
object is aliased. If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17
>>> print(a)
[17, 2, 3]
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you
are working with mutable objects. For immutable objects like strings, aliasing is not as much of a
problem. In this example:
a = 'banana'
b = 'banana'
it almost never makes a difference whether a and b refer to the same string or not.
List arguments
When you pass a list to a function, the function gets a reference to the list. If the function modifies a list
parameter, the caller sees the change. For example, delete_head removes the first element from a list:
def delete_head(t):
del t[0]
37
PYTHON PROGRAMMING
The parameter t and the variable letters are aliases for the same object. It is important to distinguish
between operations that modify lists and operations that create new lists. For example, the append method
modifies a list, but the + operator creates a new list:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1) [1, 2, 3]
>>> print(t2)
None
>>> t3 = t1 + [3]
>>> print(t3)
[1, 2, 3]
>>> t2 is t3
False
This difference is important when you write functions that are supposed to modify lists. For example,
this function does not delete the head of a list:
def bad_delete_head(t):
t = t[1:] # WRONG!
The slice operator creates a new list and the assignment makes t refer to it, but none of that has any effect
on the list that was passed as an argument.
An alternative is to write a function that creates and returns a new list. For example, tail returns all but
the first element of a list:
def tail(t):
return t[1:]
This function leaves the original list unmodified. Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print(rest)
['b', 'c']
Exercises:
1. Write a Python program to remove duplicates from a list.
2. Write a function called chop that takes a list and modifies it, removing the first and last elements,
and returns None. Then write a function called middle that takes a list and returns a new list that
contains all but the first and last elements.
38
PYTHON PROGRAMMING
39