0% found this document useful (0 votes)
58 views

Functions Files Notes Python

The document discusses functions in Python, including defining functions with def, calling functions, passing arguments to functions, different types of variables like local and global variables, and built-in library functions like those for generating random numbers from the random module. Functions allow breaking programs into smaller, reusable parts to perform specific tasks, and concepts like scope determine where variables can be accessed within a program.

Uploaded by

Prince K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Functions Files Notes Python

The document discusses functions in Python, including defining functions with def, calling functions, passing arguments to functions, different types of variables like local and global variables, and built-in library functions like those for generating random numbers from the random module. Functions allow breaking programs into smaller, reusable parts to perform specific tasks, and concepts like scope determine where variables can be accessed within a program.

Uploaded by

Prince K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT-II (SEC)

Chapter 5: Functions
A function is a group of statements that exist within a program for the purpose of performing a specific
task. Instead of writing a large program as one long sequence of statements, it can be written as several small
functions, each one performing a specific part of the task.
These small functions can then be executed in the desired order to perform the overall task. This
approach is sometimes called divide and conquer because a large task is divided into several smaller tasks that
are easily performed.
Python gives you many built-in functions like print(), etc. but you can also create your own functions. These
functions are called user-defined functions.

Defining a Function :
You can define functions to provide the required functionality. Here are simple rules to define a function in
Python.
● Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
● Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
● The code block within every function starts with a colon (:) and is indented.
● The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.
Syntax:To create a function you write its definition. Here is the general format of a function definition in
Python:
def function name():
statement
statement
etc.
Beginning at the next line is a set of statements known as a block. A block is simply a set of statements
that belong together as a group. These statements are performed any time the function is executed.
Ex:
def message():
print('I am Arthur,')
print('King of the Britons.')
Calling a Function:
A function definition specifies what a function does, but it does not cause the function to execute. To
execute a function, you must call it. This is how we would call the message function:
message()
When a function is called, the interpreter jumps to that function and executes the statements in its block.

Indentation in Python::
In Python, each line in a block must be indented. As shown in Figure 5-7, the last indented line after a
function header is the last line in the function’s block
Designing a Program to Use Functions:
The Programmers commonly use a technique known as top-down design to break down an algorithm
into functions. In a Flowcharting a Program with Functions: In flowcharts as a tool for designing programs.
In a flowchart, a function call is shown with a rectangle that has vertical bars at each side, as shown in
Figure. The name of the function that is being called is written on the symbol. The example shown in Figure
shows how we would represent a call to the message function.

Local Variables:
A local variable is created inside a function and cannot be accessed by statements that are outside the
function. Different functions can have local variables with the same names because the functions cannot see
each other’s local variables.
(The term local is meant to indicate that the variable can be used only locally, within the function in which it is
created.)

The main function calls the get_name function in line 3. Then, the statement in line 4 tries to access the name
variable. This results in an error because the name variable is local to the get_name function, and statements in
the main function cannot access it.

Scope and Local Variables:


A variable’s scope is the part of a program in which the variable may be accessed. A variable is visible
only to statements in the variable’s scope. A local variable’s scope is the function in which the variable is
created.
A function’s local variables are hidden from other
functions, the other functions may have their own local
variables with the same name. For example, look at
Program 5-5. In addition to the main function, this
program has two other functions: texas and cali- fornia.
These two functions each have a local variable named
birds.

Passing Arguments to Functions:


Pieces of data that are sent into a function are
known as arguments. The function can use its
arguments in calculations or other operations.

Concept: An argument is any piece of data that is


passed into a function when the function is called. A
parameter is a variable that receives an argument that
is passed into a function.

When this program runs, the main function is called in line 15. Inside the main function, line 5 creates a
local variable named value, assigned the value 5. Then the following state- ment in line 6 calls the show_double
function:
show_double(value)
Notice that value appears inside the parentheses. This means that value is being passed as an argument
to the show_double function, as shown in Figure 5-13 When this state- ment executes, the show_double
function will be called, and the number parameter will be assigned the same value as the value variable. This is
shown in Figure .
Global Variables:
A global variable is accessible to all the functions in a program file.
● Most programmers agree that you should restrict the use of global variables, or not use them at all. The
reasons are as follows:
● Global variables make debugging difficult. Any statement in a program file can change the value of a global
variable. If you find that the wrong value is being stored in a global variable, you have to track down every
statement that accesses it to determine where the bad value is coming from. In a program with thousands of
lines of code, this can be difficult.
● Functions that use global variables are usually dependent on those variables. If you want to use such a
function in a different program, most likely you will have to redesign it so it does not rely on the global
variable.
● Global variables make a program hard to understand. A global variable can be modified by any statement in
the program. If you are to understand any part of the program that uses a global variable, you have to be
aware of all the other parts of the program that access the global variable.

Global Constants:
A global constant is a global name that references a value that cannot be changed. Because a global
constant’s value cannot be changed during the program’s execution,
The Python language does not allow you to create true global constants, you can simulate them with
global variables. If you do not declare a global variable with the global key word inside a function, then you
cannot change the variable’s assignment inside that function.

Value-Returning Functions:
A value-returning function is a function that returns a value back to the part of the program that called it.
Python, as well as most other programming languages, provides a library of prewritten functions that perform
commonly needed tasks. These libraries typically contain a function that generates random numbers.

A value-returning function is a special type of function. It is like a void function in the following ways.
• It is a group of statements that perform a specific task.
• When you want to execute the function, you call it.
The value that is returned from a function can be used like any other value: it can be assigned to a variable,
displayed on the screen, used in a mathematical expression (if it is a number), and so on.

Standard Library Functions:


Python, as well as most other programming languages, comes with a standard library of functions that
have already been written for you. These functions, known as library functions, Some of Python’s library
functions are built into the Python interpreter. If you want to use one of these built-in functions in a program,
you simply call the function.
Many of the functions in the standard library, however, are stored in files that are known as modules.
These modules, which are copied to your computer when you install Python, help organize the standard library
functions. For example, functions for performing math operations are stored together in a module, functions for
working with files are stored together in another module, and so on.

Generating Random Numbers:


Random numbers are useful for lots of different programming tasks. The following are just a few examples.
● Random numbers are commonly used in games. For example, computer games that let the player roll dice
use random numbers to represent the values of the dice. Programs that show cards being drawn from a
shuffled deck use random numbers to represent the face values of the cards.
● Random numbers are useful in simulation programs. In some simulations, the computer must randomly
decide how a person, animal, insect, or other living being will behave. Formulas can be constructed in
which a random number is used to determine various actions and events that take place in the program.
● Random numbers are useful in statistical programs that must randomly select data for analysis.
● Random numbers are commonly used in computer security to encrypt sensitive data.
Python provides several library functions for working with random numbers. These functions are stored
in a module named random in the standard library. To use any of these functions you first need to write this
import statement at the top of your program:
import random
This statement causes the interpreter to load the contents of the random module into Memory. The following
statement shows an example of how you might call the randint function.
number = random.randint (1, 100)
the random function’s return value directly to the print function,
as shown here:
print(random.randint(1, 10))
When this statement executes, the randint function is called. The
function generates a random number in the range of 1 through
10. That value is returned and then sent to the print function. As
a result, a random number in the range of 1 through 10 will be
displayed.

What is math module in Python


The math module is a standard module in Python and is always available. An import statement tells the
interpreter the name of the module that contains the function. For example, one of the Python standard modules
is named math. To use mathematical functions under this module, you have to import the module using
import math.

The math.pi and math.e Values


The math module also defines two variables, pi and e, which are assigned mathematical values for pi and e. You
can use these variables in equations that require their values.

For example, the following statement, which calculates the area of a circle, uses pi. (Notice that we use dot
notation to refer to the variable.)
area = math.pi * radius**2

The math module in the Python standard library contains several functions that are useful for
performing mathematical operations. Table 5-2 lists many of the functions in the math module. These functions
typically accept one or more values as arguments, perform a mathematical operation using the arguments, and
return the result.
# This program demonstrates the sqrt function.
import math

def main():
# Get a number.
number = float(input('Enter a number: '))

# Get the square root of the number.


square_root = math.sqrt(number)

# Display the square root.


print('The square root of', number, 'is', square_root)

# Call the main function.


main()

output is:
Enter a number: 25
The square root of 25.0 is 5.0

For example, one of the functions is named sqrt. The


sqrt function accepts an argument and returns the square
root of the argument. Here is an example
result = math.sqrt(16)
This statement calls the sqrt function, passing 16 as an argument. The function returns the square root of 16,
which is then assigned to the result variable
Example: program to demonstarte math module
import math
print('ceil value:',math.ceil(1.001))
print('sqrt of 4:',math.sqrt(4))
print('floor value:',math.floor(1.002))
print('factorial value of 10:',math.factorial(10))
print('truncate value:',math.trunc(1.003))
print('greatest common divisor value:',math.gcd(10,125))
print('sin value',math.sin(8.0))
print('cos value',math.cos(8.0))
print('tan value',math.tan(8.0))
print('power value',math.pow(8,2))
output generated as:
ceil value: 2
sqrt of 4: 2.0
floor value: 1
factorial value of 10: 3628800
truncate value: 1
greatest common divisor value: 5
sin value 0.9893582466233818
cos value -0.14550003380861354
tan value -6.799711455220379
power value 64.0

Generating Random numbers (or) Random Number Functions:


Random numbers are used for games, simulations, testing, security, and privacy applications. Python
includes following functions that are commonly used.

Sr.No. Function & Description

1
choice(seq) :A random item from a list, tuple, or string.

2
randrange ([start,] stop [,step]) : A randomly selected element from range(start, stop, step)

3
random() :A random float r, such that 0 is less than or equal to r and r is less than 1

4
seed([x]) :Sets the integer starting value used in generating random numbers. Call this function
before calling any other random module function. Returns None.

randrange():
Description :The method randrange() returns a randomly selected element from range(start, stop, step).
Syntax: randrange ([start,] stop [,step])
Parameters are
start − Start point of the range. This would be included in the range.
stop − Stop point of the range. This would be excluded from the range.
step − Steps to be added in a number to decide a random number.
Note − This function is not accessible directly, so we need to import random
module and then we need to call this function using random static object.
randint() function:
The following statement shows an example of how you might call the randint function.
number = random.randint (1, 100)
The part of the statement that reads random.randint(1, 100) is a call to the randint function.

Example:1

Program 5-16 shows a complete program that uses the randint function. The statement in line 2 generates a
random number in the range of 1 through 10 and assigns it to the number variable

EX:2 random module:


import random
print ('choice([1, 2, 3, 5, 9]) : ', random.choice([1, 2, 3, 5, 9]))
print ('randrange(100, 1000, 2) : ', random.randrange(100, 1000, 2))
print('random()',random.random())
random.seed(20)
# It will generate same random number
print('random number with seed 10',random.random())
random.seed(20)
# It will generate same random number
print('random number with seed 10',random.random())
print('random number with seed 10',random.random())
o/p:
choice([1, 2, 3, 5, 9]) : 2
randrange(100, 1000, 2) : 374
random() 0.37791711212253254
random number with seed 10 0.9056396761745207
random number with seed 10 0.9056396761745207
random number with seed 10 0.6862541570267026

User defined Module: (or) storing Functions in Modules:


A module allows you to logically organize your Python code. Grouping related code into a module
makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that
you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A
module can also include runnable code.
Suppose your instructor has asked you to write a program that calculates the following:
• The area of a circle
• The circumference of a circle
• The area of a rectangle
• The perimeter of a rectangle
There are obviously two categories of calculations required in this program: those related to circles, and those
related to rectangles. You could write all of the circle-related functions in one module, and the rectangle-related
functions in another module. Program 5-26 shows the circle module. The module contains two function
definitions: area (which returns the area of a circle) and circumference (which returns the circumference of a
circle).

Notice that both of these files contain function definitions, but they do not contain code that calls the
functions. That will be done by the program or programs that import these modules.

Before continuing, we should mention the following things about module names:
• A module’s file name should end in .py. If the module’s file name does not end in .py you will not be able to
import it into other programs.
• A module’s name cannot be the same as a Python key word. An error would occur, for example, if you named
a module for.
The import Statement
Any Python source file as a module by executing an import statement in some other Python source file.
The import has the following syntax −
import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the module if the module is present in
the search path. A search path is a list of directories that the interpreter searches before importing a module.
For example, to import the module support.py, you need to put the following command at the top of the script.
# Import module support
import support

# Now you can call defined function that module as follows


support.print_func("Zara")

When the above code is executed, it produces the following result −


Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents the
module execution from happening over and over again if multiple imports occur.
Chapter-6: Files and Exceptions
1. Introduction to File 2. File types: Input and Output
3 Using Loops to Process Files 4 Processing Records

1.Introduction to File:
When a program needs to save data for later use, it writes the data in a file. The data can be read from
the file at a later time. The programs you have written so far require the user to reenter data each time the
program runs, because data that is stored in RAM (referenced by variables) disappears once the program stops
running.
If a program is to retain data between the times it runs, it must have a way of saving it. Data is saved in a
file, which is usually stored on a computer’s disk. Once the data is saved in a file, it will remain there after the
program stops running. Data that is stored in a file can be retrieved and used at a later time.

Most of the commercial software packages that you use on a day-to-day basis store data in files.
The following are a few examples.
• Word processors. Word processing programs are used to write letters, memos, reports, and other documents.
The documents are then saved in files so they can be edited and printed.
• Image editors. Image editing programs are used to draw graphics and edit images such as the ones that you
take with a digital camera. The images that you create or edit with an image editor are saved in files.
• Spreadsheets. Spreadsheet programs are used to work with numerical data. Numbers and mathematical
formulas can be inserted into the rows and columns of the spreadsheet. The spreadsheet can then be saved in a
file for use later.
• Games. Many computer games keep data stored in files.
• Web browers. Sometimes when you visit a Web page, the browser stores a small file known as a cookie on
your computer. Cookies typically contain information about the browsing session, such as the contents of a
shopping cart.

2. File types: Input and Output


Programmers usually refer to the process of saving data in a file as “writing data to” the file. When a
piece of data is written to a file, it is copied from a variable in RAM to the file. This is illustrated in Figure 6-1.
The term output file is used to describe a file that data is written to. It is called an output file because the
program stores output in it.
Figure 6-2 illustrates this. The term input file is used to describe a file that data is read from. It is called
an input file because the program gets input from the file.
The process how to write data to files and read data from files. There are always three steps that must be
taken when a file is used by a program.

i). Open the file—Opening a file creates a connection between


the file and the program. Opening an output file usually creates
the file on the disk and allows the program to write data to it.
Opening an input file allows the program to read data from the
file.

ii). Process the file—In this step data is either written to the file
(if it is an output file) or read from the file (if it is an input file).

iii). Close the file—When the program is finished using the


file, the file must be closed. Closing a file disconnects the file
from the program.
3. Using Loops to Process Files:
Files usually hold large amounts of data, and programs typically use a loop to process the data in a file.
some programs use files to store only small amounts of data, files are typically used to hold large collections of
data. When a program uses a file to write or read a large amount of data, a loop is typically involved.

For example, look at the code in Program 6-8. This program gets sales amounts for a series of days from
the user and writes those amounts to a file named sales.txt. The user specifies the number of days of sales data
he or she needs to enter. In the sample run of the program, the user enters sales amounts for five days.

4. Processing Records
The data that is stored in a file is frequently organized in records. A record is a complete set of data
about an item, and a field is an individual piece of data within a record.
When data is written to a file, it is often organized into records and fields. A record is a complete set of
data that describes one item, and a field is a single piece of data within a record. For example, suppose we want
to store data about employees in a file. The file will contain a record for each employee. Each record will be a
collection of fields, such as name, ID number, and department. This is illustrated in Figure 6-18.

Each time you write a record to a sequential access file, you write the fields that make up the record, one
after the other. For example, Figure 6-19 shows a file that contains three employee records. Each record consists
of the employee’s name, ID number, and department.
Chapter-7:Lists and Tuples

I. Sequences:
A sequence is an object that holds multiple items of data, stored one after the other. You can perform
operations on a sequence to examine and manipulate the items stored in it.

II. Introduction to Lists:


● A list is an object that contains multiple data
items.
● Lists are mutable, which means that their contents
can be changed during a program’s execution.
● Lists are dynamic data structures, meaning that
items may be added to them or removed from
them.
● You can use indexing, slicing, and various
methods to work with lists in a program

A list is an object that contains multiple data items.


Each item that is stored in a list is called an element.
Here is a statement that creates a list of integers:
even_numbers = [2, 4, 6, 8, 10]
The items that are enclosed in brackets and separated
by commas are the list elements. After this statement
executes, the variable even_numbers will reference
the list

The Repetition Operator:


The * symbol multiplies two numbers. However, when the operand on the left side of the * symbol is a
sequence (such as a list) and the operand on the right side is an integer, it becomes the repetition operator. The
repetition operator makes multiple copies of a list and joins them all together.
Here is the general format: list * n
In the general format, list is a list and n is the number of copies to make. The following session demonstrates:
1 >>> numbers = [0] * 5
2 >>> print(numbers)
3 [0, 0, 0, 0, 0]
4 >>>
in line 1 the expression [0] * 5 makes five copies of the list [0] and joins them all together in a single list.

Here is another interactive mode demonstration:


1 >>> numbers = [1, 2, 3] * 3
2 >>> print(numbers) e
3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
4 >>>
Iterating over a List with the for Loop:
There are techniques for accessing the individual characters in a string. Many of the same programming
techniques also apply to lists. For example, you can iterate over a list with the for loop, as shown here:
numbers = [99, 100, 101, 102]
for n in numbers:
print(n)

If we run this code, it will print:


99
100
101
102
Indexing:
Another way that you can access the individual elements in a list is with an index. Each element in a list
has an index that specifies its position in the list. Indexing starts at 0, so the index of the first element is 0, the
index of the second element is 1, and so forth. The index of the last element in a list is 1 less than the number of
elements in the list.

For example, the following statement creates a list with 4 elements:


my_list = [10, 20, 30, 40]

The indexes of the elements in this list are 0, 1, 2, and 3. We can print the elements of the list with the following
statement:
print(my_list[0], my_list[1], my_list[2], my_list[3])

The following loop also prints the elements of the list:


index = 0
while index < 4:
print(my_list[index])
index += 1

The index 21 identifies the last element in a list, 22 identifies the next to last element, and so forth. The
following code shows an example:
my_list = [10, 20, 30, 40]
print(my_list[−1], my_list[−2], my_list[−3], my_list[−4])
In this example, the print function will display:
40 30 20 10

The len Function:


Python has a built-in function named len that returns the length of a sequence, such as a list. The
following code demonstrates:
my_list = [10, 20, 30, 40]
size = len(my_list)

The first statement assigns the list [10, 20, 30, 40] to the my_list variable. The second statement calls the len
function, passing the my_list variable as an argument.
The function returns the value 4, which is the number of elements in the list. This value is assigned to the size
variable.

The len function can be used to prevent an IndexError exception when iterating over a list with a loop. Here is
an example:

my_list = [10, 20, 30, 40]


index = 0
while index < len(my_list):
print(my_list[index])
index += 1

Lists Are Mutable


Lists in Python are mutable, which means their elements can be changed. Consequently, an expression
in the form list[index] can appear on the left side of an assignment operator.
The following code shows an example:
1 numbers = [1, 2, 3, 4, 5]
2 print(numbers)
3 numbers[0] = 99
4 print(numbers)

The statement in line 2 will display [1, 2, 3, 4, 5]

The statement in line 3 assigns 99 to numbers[0]. This changes the first value in the list to 99. When the
statement in line 4 executes, it will display [99, 2, 3, 4, 5]

Concatenating Lists
To concatenate means to join two things together. You can use the + operator to concatenate two lists. Here
is an example:
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
list3 = list1 + list2
After this code executes, list1 and list2 remain unchanged, and list3 references the following list:
[1, 2, 3, 4, 5, 6, 7, 8]
The following interactive mode session also demonstrates list concatenation:
>>> girl_names = ['Joanne', 'Karen', 'Lori']
>>> boy_names = ['Chris', 'Jerry', 'Will']
>>> all_names = girl_names + boy_names
>>> print(all_names)
['Joanne', 'Karen', 'Lori', 'Chris', 'Jerry', 'Will']

III. List Slicing:


A slicing expression selects a range of elements from a sequence.
A slice is a span of items that are taken from a sequence. When you take a slice from a list, you get a
span of elements from within the list. To get a slice of a list, you write an expression in the following general
format:
list_name[start : end]
In the general format, start is the index of the first element in the slice, and end is the index marking the end of
the slice. The expression returns a list containing a copy of the elements from start up to (but not including)
end.
For example, suppose we create the following list:
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

The following statement uses a slicing expression to get the elements from indexes 2 up to, but not including, 5:
mid_days = days[2:5]
After this statement executes, the mid_days variable references the following list:
['Tuesday', 'Wednesday', 'Thursday']
The following interactive mode session shows an example:
1 >>> numbers = [1, 2, 3, 4, 5]
2 >>> print(numbers)
3 [1, 2, 3, 4, 5]
4 >>> print(numbers[:3])
5 [1, 2, 3]
6 >>>
Notice that line 4 sends the slice numbers[:3] as an argument to the print function. Because the starting index
was omitted, the slice contains the elements from index 0 up to 3.

Python uses the length of the list as the end index. The following interactive mode session shows an example:
1 >>> numbers = [1, 2, 3, 4, 5] e
2 >>> print(numbers) e
3 [1, 2, 3, 4, 5]
4 >>> print(numbers[2:]) e
5 [3, 4, 5]
6 >>>
Notice that line 4 sends the slice numbers[2:] as an argument to the print function. Because the ending index
was omitted, the slice contains the elements from index 2 through the end of the list.

The following interactive mode session shows an example of a slicing expression with a step value:
1 >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2 >>> print(numbers)
3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4 >>> print(numbers[1:8:2])
5 [2, 4, 6, 8]
6 >>>
In the slicing expression in line 4, the third number inside the brackets is the step value. A step value of 2, as
used in this example, causes the slice to contain every second element from the specified range in the list.

Python adds a negative index to the length of a list to get the position referenced by that index. The following
interactive mode session shows an example:
1 >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2 >>> print(numbers)
3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4 >>> print(numbers[-5:])
5 [6, 7, 8, 9, 10]
6 >>>

IV. Finding Items in Lists with the in Operator:


You can search for an item in a list using the in operator, In Python you can use the in operator to determine
whether an item is contained in a list. Here is the general format of an expression written with the in operator to
search for an item in a list:
item in list
In the general format, item is the item for which you are searching, and list is a list. The expression returns true
if item is found in the list or false otherwise, see the following example:
1 # This program demonstrates the in operator
2 # used with a list.
3
4 def main():
5 # Create a list of product numbers.
6 prod_nums = ['V475', 'F987', 'Q143', 'R688']
7
8 # Get a product number to search for.
9 search = input('Enter a product number: ')
10
11 # Determine whether the product number is in the list.
12 if search in prod_nums:
13 print(search, 'was found in the list.')
14 else:
15 print(search, 'was not found in the list.')
16
17 # Call the main function.
18 main()

Program Output (with input shown in bold)


Enter a product number: Q143 e
Q143 was found in the list.

Program Output (with input shown in bold)


Enter a product number: B000 e
B000 was not found in the list

You can use the not in operator to determine whether an item is not in a list. Here is an example:
if search not in prod_nums:
print(search, 'was not found in the list.')
else:
print(search, 'was found in the list.')

V. List Methods and Useful Built-in Functions


Lists have numerous methods that allow you to work with the elements that they contain. Python also provides
some built-in functions that are useful for working with lists.

The append Method


The append method is commonly used to add items to a list. The item that is passed as an argument is appended
to the end of the list’s existing elements

The sort Method


The sort method rearranges the elements of a list so they appear in ascending order (from the lowest value to the
highest value). Here is an example:
my_list = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
print('Original order:', my_list)
my_list.sort()
print('Sorted order:', my_list)
The remove Method
The remove method removes an item from the list. You pass an item to the method as an argument, and the first
element containing that item is removed. This reduces the size of the list by one element. All of the elements
after the removed element are shifted one position toward the beginning of the list
(remove_item.py)
1 # This program demonstrates how to use the remove
2 # method to remove an item from a list.
3
4 def main():
5 # Create a list with some items.
6 food = ['Pizza', 'Burgers', 'Chips']
7
8 # Display the list.
9 print('Here are the items in the food list:')
10 print(food)
11
12 # Get the item to change.
13 item = input('Which item should I remove? ')
14
15 try:
16 # Remove the item.
17 food.remove(item)
18
19 # Display the list.
20 print('Here is the revised list:')
21 print(food)
22
23 except ValueError:
24 print('That item was not found in the list.')
25
26 # Call the main function.
27 main()

Program Output (with input shown in bold)


Here are the items in the food list:
['Pizza', 'Burgers', 'Chips']
Which item should I remove? Burgers
Here is the revised list:
['Pizza', 'Chips']

The reverse Method


The reverse method simply reverses the order of the items in the list. Here is an example:
my_list = [1, 2, 3, 4, 5]
print('Original order:', my_list)
my_list.reverse()
print('Reversed:', my_list)

This code will display the following:


Original order: [1, 2, 3, 4, 5]
Reversed: [5, 4, 3, 2, 1]
The del Statement:
The remove method that you saw earlier removes a specific item from a list, if that item is in the list.
Some situations might require that you remove an element from a specific index, regardless of the item that is
stored at that index. This can be accomplished with the del statement. Here is an example of how to use the del
statement:
my_list = [1, 2, 3, 4, 5]
print('Before deletion:', my_list)
del my_list[2]
print('After deletion:', my_list)

This code will display the following:


Before deletion: [1, 2, 3, 4, 5]
After deletion: [1, 2, 4, 5]

The min and max Functions


Python has two built-in functions named min and max that work with sequences. The min function
accepts a sequence, such as a list, as an argument and returns the item that has the lowest value in the sequence.
Here is an example:
my_list = [5, 4, 3, 2, 50, 40, 30]
print('The lowest value is', min(my_list))
This code will display the following:
The lowest value is 2

The max function accepts a sequence, such as a list, as an argument and returns the item that has the highest
value in the sequence.
Here is an example:
my_list = [5, 4, 3, 2, 50, 40, 30]
print('The highest value is', max(my_list))
This code will display the following:
The highest value is 50

VI. Copying Lists


To make a copy of a list, you must copy the list’s elements. Recall that in Python, assigning one variable
to another variable simply makes both variables reference the same object in memory.
For example, look at the following code:
# Create a list.
list1 = [1, 2, 3, 4]
# Assign the list to the list2 variable.
list2 = list1
To demonstrate this, look at the following interactive session:
1 >>> list1 = [1, 2, 3, 4]
2 >>> list2 = list1
3 >>> print(list1)
4 [1, 2, 3, 4]
5 >>> print(list2)
6 [1, 2, 3, 4]
7 >>> list1[0] = 99
8 >>> print(list1)
9 [99, 2, 3, 4]
10 >>> print(list2)
11 [99, 2, 3, 4]
Tuples:
A tuple is an immutable sequence, which means that its contents cannot be changed.
A tuple is a sequence, very much like a list. The primary difference between tuples and lists is that
tuples are immutable. That means that once a tuple is created, it cannot be changed. When you create a tuple,
you enclose its elements in a set of parentheses, as shown in the following interactive session:
>>> my_tuple = (1, 2, 3, 4, 5)
>>> print(my_tuple)
(1, 2, 3, 4, 5)
>>>
The following session shows how a for loop can iterate over the elements in a tuple:
>>> names = ('Holly', 'Warren', 'Ashley')
>>> for n in names:
print(n)
Holly
Warren
Ashley
>>>
Like lists, tuples support indexing, as shown in the following session:
>>> names = ('Holly', 'Warren', 'Ashley')
>>> for i in range(len(names)):
print(names[i])
Holly
Warren
Ashley
>>>
In fact, tuples support all the same operations as lists, except those that change the contents of the list.
Tuples support the following:
• Subscript indexing (for retrieving element values only)
• Methods such as index
• Built-in functions such as len, min, and max
• Slicing expressions
• The in operator
• The + and * operators
Tuples do not support methods such as append, remove, insert, reverse, and sort

Two-Dimensional Lists
A two-dimensional list is a list that has other lists as its elements. The elements of a list can be virtually
anything, including other lists. To demonstrate, look at the following interactive session:
1 >>> students = [['Joe', 'Kim'], ['Sam', 'Sue'], ['Kelly', 'Chris']]
2 >>> print(students)
3 [['Joe', 'Kim'], ['Sam', 'Sue'], ['Kelly', 'Chris']]
4 >>> print(students[0])
5 ['Joe', 'Kim']
6 >>> print(students[1]) e 7 ['Sam', 'Sue']
8 >>> print(students[2])
9 ['Kelly', 'Chris']
10 >>>
Lists of lists are also known as nested lists, or two-dimensional lists. It is common to think of a two-dimensional
list as having rows and columns of elements
==xxx==

You might also like