0% found this document useful (0 votes)
0 views43 pages

Python Lab Manual 02

The document is a lab manual for a Python Programming and Freelancing course, detailing the curriculum, lab topics, and assessment methods. It covers fundamental Python concepts, data manipulation, and freelancing practices, culminating in a comprehensive project. The course aims to equip students with practical programming skills and knowledge of freelancing platforms to succeed in the gig economy.

Uploaded by

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

Python Lab Manual 02

The document is a lab manual for a Python Programming and Freelancing course, detailing the curriculum, lab topics, and assessment methods. It covers fundamental Python concepts, data manipulation, and freelancing practices, culminating in a comprehensive project. The course aims to equip students with practical programming skills and knowledge of freelancing platforms to succeed in the gig economy.

Uploaded by

aaimarizwan2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

AI102L- Python Programming &

Freelancing Lab

Lab Manual

Prepare by: Asim Shah and Muhammad Naeem


Ghulam Ishaq Khan Institute of Engineering and Technology, Pakistan

pg. 1
Lab Breakdown

Lab Contents/Topics

Lab#01: Introduction to Python, Variables and Basic Data Types

Lab#02: Conditional Statements, Loops, Lists, Tuples and Sets

Lab#03: Dictionary, Strings and Sting Manipulation in Python

Lab#04: Functions in Python

Lab#05: OOP in Python

Lab#06: OOP Concepts in Python

Mid-term exam.

Lab#07: Python Modules and Libraries, Pandas Data Manipulation(CSV, Images ,Text)

Lab#08: Numpy, Matplotlib for Data Visualization

Lab#09: Web Scrapping with Python and Beautiful Soup

Lab#10: Intro to Freelancing Platforms, Finding and applying for jobs(Fiver)

Lab#11: Managing Freelance Projects, Financial aspects of freelancing, and building a sustainable
freelance career

Lab#12: Freelancing Session and Project Viva

Final Exam

pg. 2
I. Table of Contents

pg. 3
II. Lab Outline
Python Programming & and Knowledge Profile:
AI102 Focus: Regular AI
Freelancing Essentials (1 CH) Mathematics and Computing:
Pre-Requisite:
Instructor:
Office:
Email:

Course Introduction
The Python Programming and Freelancing Essentials course offers a comprehensive introduction to Python, covering fundamental syntax,
file handling, exception handling, and data structures. Students will gain practical experience with essential libraries for data analysis, web
development, and automation, building a solid foundation in programming applicable across various fields. Additionally, the course
includes an overview of popular freelancing platforms and best practices for freelancing, helping students leverage their Python skills to
find opportunities and succeed in the gig economy.

Course Contents
The course covers Python fundamentals, gradually progressing to more advanced topics, including data handling with NumPy and Pandas,
data visualization, and machine learning with Scikit-Learn. The curriculum also explores Natural Language Processing and Computer Vision,
culminating in a comprehensive project that integrates all the skills taught in the course. By the end, students will have a solid foundation in
Python programming and practical skills applicable to AI technologies. Additionally, the course includes an overview of popular freelancing
platforms and best practices, equipping students to effectively utilize their Python skills to secure opportunities and thrive in the freelance
marketplace.

Mapping of CLOs and PLOs


Sr. No Course Learning Outcomes PLOs Blooms Taxonomy
Demonstrate ability to use basic Python syntax and concepts to
write simple scripts and programs. Fundamental Python
CLO_1 C4 (Application)
Understand and apply basic data types, control structures, and Knowledge
built-in functions effectively.
Develop Python programs that perform file operations, data
processing, and system automation.
Identify and correct bugs in Python programs using basic
CLO_2 Practical Application C4 (Application)
debugging techniques and error handling.
Demonstrate an understanding of freelancing platforms and
best practices for securing and managing freelancing projects.
Use Python to solve typical problems and tasks that one might
encounter in academic, personal, or early professional
programming endeavors. Knowledge for solving
CLO_3 C3 (Explain)
Complete a small project that synthesizes course topics into a computing problem
practical application, demonstrating an understanding of how
Python can be used to create useful tools and solutions.
+While reading the CLOs, please add the prefix “Upon successful completion of this course, the student will be able to”
CLO Assessment Mechanism
Assessment tools CLO_1 CLO_2 CLO_3
Lab Performance 50% 30% 30%
Open Ended Lab – 10% 20%
Midterm Exam 50% 40% –
Final Exam – 20% 50%
Overall Grading Policy

pg. 4
Assessment Items Percentage
Lab Performance 40%
Open Ended Lab 10%
Midterm Exam 20%
Final Exam 30%

Text and Reference Books


Textbooks:

1. Eric Matthes, “Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming” No Starch Press, 2023.
2. Charles Severance, “Python for Everybody: Exploring Data in Python 3”, CreateSpace Independent Publishing Platform, 2016.
3. Alison Grade, “The Freelance Bible: Every Thing You Need to Go Solo in Any Industry” Portfolio Penguin, 2020.
Other Sources:

1. https://www.kaggle.com/learn/python
2. https://www.screenskills.com/developing-your-career/freelance-toolkit/core-skills-of-freelancing/

Administrative Instruction
▪ According to institute policy, 80% attendance is mandatory to appear in the final examination.
▪ Assignments must be submitted as per instructions mentioned in the assignments.
▪ For queries, kindly follow the office hours in order to avoid any inconvenience.

• Computer Usage
▪ VS code
▪ Google Colab
▪ Freelancing Platforms

Lecture Breakdown

III. System Requirements

HARDWARE REQUIREMENT

• Core i3 or Above
pg. 5
• 32- or 64-bit computer
• 4 GB RAM
• 3 GB HDD

SOFTWARE REQUIREMENT

• Anaconda, PyCharm, Visual Studio, Jupyter notebook, Jupyterlab, gitbash

Anaconda System Requirements link:


https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html

IV. Evaluation Rubrics


For Python Section only

Weekly Evaluation

Rubrics Marks (10)


Code writing 1
Error/exception Handling 1
Code Comments / Necessary Documentation 3
Correctness 5

Detailed Rubric of weekly Evaluation:

Code writing (No credit, if not relevant implementation):

* Meaningful/relevant variable/function names: 1

Error/exception Handling:

* Runs without exception: 0.5

* Displays proper messages/operations clearly: 0.5

Code Comments / Viva:

pg. 6
* Clarify meaning where needed: 1

* Knowledge about the topic: 2

Correctness:

* Accurate methodology: 1

* All tasks are done: 3

* Passes all test cases: 1

pg. 7
Lab#02 - Conditional Statements, Loops, Lists and Tuples

Objectives:
➢ To learn and to use conditional statements (if, elif, else)
➢ To learn and able to use loop (for loop, while loop)
➢ To learn and able to use the break and continue statement
➢ To learn and able to use loop with lists
➢ To learn and able to use loop with tuples and methods
➢ To learn and able to create, modify lists and access their elements
➢ To learn and able to use slicing in lists
➢ To learn and able to create and use tuples and tuples packing and unpacking.

Outcomes:

Students should be able to know the if, elif and else.
➢ Students should be able to use loops for loop and while loop in the programs.
➢ Students should be able to use break and continue statement with loop.
➢ Students should be able to use loops with lists
➢ Students should be able to create, modify lists and access their elements
➢ Students should be able to use slicing in lists
➢ Student should be able to create and use tuples and tuples packing and unpacking

2.1 Conditional Statements

In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution
of a statement or group of statements based on the value of an expression.

2.1.1 Introduction to the if Statement

We’ll start by looking at the most basic type of if statement. In its simplest form, it looks like this:

In the form shown above:

• <expr> is an expression evaluated in a Boolean context, as discussed in the section on Logical Operators in the
Operators and Expressions in Python tutorial.
• <statement> is a valid Python statement, which must be indented. (You will see why very soon.)
If <expr> is true (evaluates to a value that is “truthy”), then <statement> is executed. If <expr> is false, then <statement> is
skipped over and not executed.

Note that the colon (:) following <expr> is required. Some programming languages require <expr> to be enclosed in
parentheses, but Python does not.

pg. 8
Here are several examples of this type of if statement:

2.1.2 Grouping Statements: Indentation and Blocks

In all the examples shown above, each if <expr>: has been followed by only a single <statement>. There needs to be some
way to say “If <expr> is true, do all of the following things.”

The usual approach taken by most programming languages is to define a syntactic device that groups multiple statements
into one compound statement or block. A block is regarded syntactically as a single entity. When it is the target of an if
statement, and <expr> is true, then all the statements in the block are executed. If <expr> is false, then none of them are.

Virtually all programming languages provide the capability to define blocks, but they don’t all provide it in the same way.
Let’s see how Python does it.

In a Python program, contiguous statements that are indented to the same level are considered to be part of the same
block.

Here, all the statements at the matching indentation level (lines 2 to 5) are considered part of the same block. The entire
block is executed if <expr> is true or skipped over if <expr> is false. Either way, execution proceeds with
<following_statement> (line 6) afterward.

pg. 9
Notice that there is no token that denotes the end of the block. Rather, the end of the block is indicated by a line that is
indented less than the lines of the block itself.

Consider the following code.

The four print() statements on lines 4 to 8 are indented to the same level as one another. They constitute the block that would
be executed if the condition were true. But it is false, so all the statements in the block are skipped. After the end of the
compound if statement has been reached (whether the statements in the block on lines 4 to 8 are executed or not), execution
proceeds to the first statement having a lesser indentation level: the print() statement on line 9.

Blocks can be nested to arbitrary depth. Each indent defines a new block, and each out dent ends the preceding block. The
resulting structure is straightforward, consistent, and intuitive.

Consider this complex example and check the output generated when this code is run is shown below:

2.1.3 The else and elif Clauses.

Now you know how to use an if statement to conditionally execute a single statement or a block of several statements. It’s
time to find out what else you can do.

pg. 10
Sometimes, you want to evaluate a condition and take one path if it is true but specify an alternative path if it is not. This is
accomplished with an else clause:

If <expr> is true, the first suite is executed, and the second is skipped. If <expr> is false, the first suite is skipped and the
second is executed. Either way, execution then resumes after the second suite. Both suites are defined by indentation, as
described above.

In this example, x is less than 50, so the first suite (lines 4 to 5) is executed, and the second suite (lines 7 to 8) are skipped:

Here, on the other hand, x is greater than 50, so the first suite is passed over, and the second suite executed:

There is also syntax for branching execution based on several alternatives. For this, use one or more elif (short for else if)
clauses. Python evaluates each <expr> in turn and executes the suite corresponding to the first that is true. If none of the
expressions are true, and an else clause is specified, then its suite is executed:

pg. 11
An arbitrary number of elif clauses can be specified. The else clause is optional. If it is present, there can be only one, and
it must be specified last:

At most, one of the code blocks specified will be executed. If an else clause isn’t included, and all the conditions are false,
then none of the blocks will be executed.

Multiple statements may be specified on the same line as an elif or else clause as well

Ans shown below:

2.1.4 Conditional Expressions (Python’s Ternary Operator)

Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional
operator or ternary operator in various places in the Python documentation.)
pg. 12
In its simplest form, the syntax of the conditional expression is as follows:

This is different from the if statement forms listed above because it is not a control structure that directs the flow of program
execution. It acts more like an operator that defines an expression. In the above example, <conditional_expr> is evaluated
first. If it is true, the expression evaluates to <expr1>. If it is false, the expression evaluates to <expr2>.

Notice the non-obvious order: the middle expression is evaluated first, and based on that result, one of the expressions on
the ends is returned. Here are some examples that will hopefully help clarify:

Remember that the conditional expression behaves like an expression syntactically. It can be used as part of a longer
expression. The conditional expression has lower precedence than virtually all the other operators, so parentheses are needed
to group it by itself.

In the following example, the + operator binds more tightly than the conditional expression, so 1 + x and y + 2 are evaluated
first, followed by the conditional expression. The parentheses in the second case are unnecessary and do not change the
result:

If you want the conditional expression to be evaluated first, you need to surround it with grouping parentheses. In the next
example, (x if x > y else y) is evaluated first. The result is y, which is 40, so z is assigned 1 + 40 + 2 = 43:

pg. 13
2.2 Loops in Python

2.2.1 While loop

The format of a basic while loop is shown below:

<statement(s)> represents the block to be repeatedly executed, often referred to as the body of the loop. This is denoted with
indentation, just as in an if statement.

The controlling expression, <expr>, typically involves one or more variables that are initialized prior to starting the loop
and then modified somewhere in the loop body.

When a while loop is encountered, <expr> is first evaluated in Boolean context. If it is true, the loop body is executed. Then
<expr> is checked again, and if still true, the body is executed again. This continues until <expr> becomes false, at which
point program execution proceeds to the first statement beyond the loop body.

Consider this loop:

Here’s what’s happening in this example:

• n is initially 5. The expression in the while statement header on line 2 is n > 0, which is true, so the loop body
executes. Inside the loop body on line 3, n is decremented by 1 to 4, and then printed.
• When the body of the loop has finished, program execution returns to the top of the loop at line 2, and the expression
is evaluated again. It is still true, so the body executes again, and 3 is printed.

pg. 14
• This continues until n becomes 0. At that point, when the expression is tested, it is false, and the loop terminates.
Execution would resume at the first statement following the loop body, but there isn’t one in this case.

Note that the controlling expression of the while loop is tested first before anything else happens. If it’s false to start with,
the loop body will never be executed at all:

In the example above, when the loop is encountered, n is 0. The controlling expression n > 0 is already false, so the loop
body never executes.

Here’s another while loop involving a list, rather than a numeric comparison:

When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty. In this example, a is
true as long as it has elements in it. Once all the items have been removed with the .pop() method and the list is empty, a is
false, and the loop terminates.

2.2.2 For loop

2.2.2.1 Three-Expression Loop

Another form of for loop popularized by the C programming language contains three parts:

• An initialization
• An expression specifying an ending condition
• An action to be performed at the end of each iteration.
This type of loop has the following form:

pg. 15
This loop is interpreted as follows:

• Initialize i to 1.
• Continue looping as long as i <= 10.
• Increment i by 1, after iteration of each loop.
Three-expression for loops are popular because the expressions specified for the three parts can be nearly anything, so this
has quite a bit more flexibility than the simpler numeric range from shown above. These for loops are also featured in the
C++, Java, PHP, and Perl languages.

In python

2.2.2.2 The range() Function

range(<end>) returns an iterable that yields integers starting with 0, up to but not including <end>:

In Python, iterable means an object can be used in iteration.

Note that range() returns an object of class range, not a list or tuple of the values. Because a range object is an iterable, you
can obtain the values by iterating over them with a for loop:

pg. 16
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a
parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding
a third parameter: range(2, 30, 3): range(start, end, increment)

2.2.2.3 Loop for list

To iterate over a list, you use the for loop statement as follows:

In this syntax, the for loop statement assigns an individual element of the list to the item variable in each iteration.

pg. 17
Inside the body of the loop, you can manipulate each list element individually.

For example, the following defines a list of cities and uses a for loop to iterate over the list:

In this example, the for loop assigns an individual element of the cities list to the city variable and prints out the city in each
iteration.

2.3 Using Python for loop to iterate over a list with index

Sometimes, you may want to access indexes of elements inside the loop. In these cases, you can use the enumerate()
function.

The enumerate() function returns a tuple that contains the current index and element of the list.

The following example defines a list of cities and uses a for loop with the enumerate() function to iterate over the list:

To access the index, you can unpack the tuple within the for loop statement like this:

pg. 18
The enumerate() function allows you to specify the starting index which defaults to zero.

The following example uses the enumerate() function with the index that starts from one:

2.4 Break and Continue

In Python, break and continue statements can alter the flow of a normal loop.

Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current iteration
or even the whole loop without checking test expression.

The break and continue statements are used in these cases.

Break Statement

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the
body of the loop.

If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost
loop.

Syntax of break

Just use “break” in your program.


pg. 19
Flowchart of break

The working of break statement in for loop and while loop is shown below.

pg. 20
Example: Python break

In this program, we iterate through the "string" sequence. We check if the letter is i, upon which we break from the loop.
Hence, we see in our output that all the letters up till i gets printed. After that, the loop terminates.

Continue statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate
but continues on with the next iteration.

Syntax of Continue
Just use “continue” in your program.

Flowchart of continue

The working of the continue statement in for and while loop is shown below.
pg. 21
Example: Python continue

This program is same as the above example except the break statement has been replaced with continue.

We continue with the loop, if the string is i, not executing the rest of the block. Hence, we see in our output that all the
letters except i gets printed.

Tasks:

pg. 22
2.5 Lists

List is a collection of anything, it is like an array in many other programming languages, but it can be used for more things.
Python lists are made by putting a comma-separated sequence of objects in square brackets ([]), as shown in the picture
below.

The important characteristics of Python lists are as follows:

• Lists are ordered.


• Lists can contain any arbitrary objects.
• List elements can be accessed by index.
• Lists can be nested to arbitrary depth.
• Lists are mutable.
• Lists are dynamic.

Each of these features is examined in more detail below.

Lists Are Ordered

A list is not merely a collection of objects. It is an ordered collection of objects. The order in which you specify the elements
when you define a list is an innate characteristic of that list and is maintained for that list’s lifetime.

Lists that have the same elements in a different order are not the same:

Lists Can Contain Arbitrary Objects


A list can contain any assortment of objects. The elements of a list can all be the same type:

pg. 23
Or the elements can be of varying types:

Lists can even contain complex objects, like functions, classes, and modules, which you will learn about in upcoming labs:

A list can contain any number of objects, from zero to as many as your computer’s memory will allow:

pg. 24
(A list with a single object is sometimes referred to as a singleton list.)

List objects needn’t be unique. A given object can appear in a list multiple time:

List Elements Can Be Accessed by Index

Individual elements in a list can be accessed using an index in square brackets. This is exactly analogous to accessing
individual characters in a string. List indexing is zero-based as it is with strings.

Consider the following list:

The indices for the elements are shown below:

pg. 25
Here is Python code to access some elements of a list:

Virtually everything about string indexing works similarly for lists. For example, a negative list index counts from the end
of the list:

2.5.1 List Slicing

Slicing also works. If a is a list, the expression a[m:n] returns the portion of a from index m to, but not including, index n:

Example: a[start : end]

pg. 26
Other features of string slicing work analogously for list slicing as well:

Both positive and negative indices can be specified:

Omitting the first index starts the slice at the beginning of the list, and omitting the second index extends the slice to the end
of the list:

Example: a[start : end : increment]

The syntax for reversing a list works the same way it does for strings:

pg. 27
The [:] syntax works for lists. However, there is an important difference between how this operation works with a list and
how it works with a string.

If s is a string, s[:] returns a reference to the same object:

Conversely, if a is a list, a[:] returns a new object that is a copy of a:

Several Python operators and built-in functions can also be used with lists in ways that are analogous to strings:

The in and not in operators:

The concatenation (+) and replication (*) operators:


pg. 28
The len(), min(), and max() functions:

It’s not an accident that strings and lists behave so similarly. They are both special cases of a more general object type called
an iterable, which you will encounter in more detail in the upcoming labs on definite iteration.

By the way, in each example above, the list is always assigned to a variable before an operation is performed on it. But you
can operate on a list literal as well:

For that matter, you can do likewise with a string literal:

pg. 29
2.5.2 Lists Can Be Nested

You have seen that an element in a list can be any sort of object. That includes another list. A list can contain sub lists,
which in turn can contain sub lists themselves, and so on to arbitrary depth.

Consider this (admittedly contrived) example:

The object structure that x references is diagrammed below:

x[0], x[2], and x[4] are strings, each one character long:

But x[1] and x[3] are sub lists:

To access the items in a sub list, simply append an additional index:

pg. 30
x[1][1] is yet another sub list, so adding one more index accesses its elements:

There is no limit, short of the extent of your computer’s memory, to the depth or complexity with which lists can be nested
in this way.

All the usual syntax regarding indices and slicing applies to sub lists as well:

However, be aware that operators and functions apply to only the list at the level you specify and are not recursive. Consider
what happens when you query the length of x using len():

pg. 31
x has only five elements—three strings and two sublists. The individual elements in the sublists don’t count toward x’s
length.

You’d encounter a similar situation when using the in operator:

'ddd' is not one of the elements in x or x[1]. It is only directly an element in the sublist x[1][1]. An individual element in a
sublist does not count as an element of the parent list(s).

2.5.3 Lists Are Mutable

Most of the data types you have encountered so far have been atomic types. Integer or float objects, for example, are
primitive units that can’t be further broken down. These types are immutable, meaning that they can’t be changed once they
have been assigned. It doesn’t make much sense to think of changing the value of an integer. If you want a different integer,
you just assign a different one.

By contrast, the string type is a composite type. Strings are reducible to smaller parts—the component characters. It might
make sense to think of changing the characters in a string. But you can’t. In Python, strings are also immutable.

pg. 32
The list is the first mutable data type you have encountered. Once a list has been created, elements can be added, deleted,
shifted, and moved around at will. Python provides a wide range of ways to modify lists.

Modifying a Single List Value

A single value in a list can be replaced by indexing and simple assignment:

You can’t do this with a string:

A list item can be deleted with the del command:

Modifying Multiple List Values

What if you want to change several contiguous elements in a list at one time? Python allows this with slice assignment,
which has the following syntax:

Again, for the moment, think of an iterable as a list. This assignment replaces the specified slice of a with <iterable>:

pg. 33
The number of elements inserted need not be equal to the number replaced. Python just grows or shrinks the list as needed.

You can insert multiple elements in place of a single element—just use a slice that denotes only one element:

Note that this is not the same as replacing the single element with a list:

You can also insert elements into a list without removing anything. Simply specify a slice of the form [n:n] (a zero-length
slice) at the desired index:

You can delete multiple elements out of the middle of a list by assigning the appropriate slice to an empty list. You can also
use the del statement with the same slice:

pg. 34
2.5.4 List Methods
Prepending or Appending Items to a List

Additional items can be added to the start or end of a list using the + concatenation operator or the += augmented assignment
operator:

Note that a list must be concatenated with another list, so if you want to add only one element, you need to specify it as a
singleton list:

Note: Technically, it isn’t quite correct to say a list must be concatenated with another list. More precisely, a list must be
concatenated with an object that is iterable. Of course, lists are iterable, so it works to concatenate a list with another list.

Strings are iterable also. But watch what happens when you concatenate a string onto a list:

This result is perhaps not quite what you expected. When a string is iterated through, the result is a list of its component
characters. In the above example, what gets concatenated onto list a is a list of the characters in the string 'corge'.

If you really want to add just the single string 'corge' to the end of the list, you need to specify it as a singleton list:

pg. 35
Methods That Modify a List

Finally, Python supplies several built-in methods that can be used to modify lists. Information on these methods is detailed
below.

• a.append(<obj>) Appends an object to a list.


a.append(<obj>) appends object <obj> to the end of list a:

Remember, list methods modify the target list in place. They do not return a new list:

Remember that when the + operator is used to concatenate to a list, if the target operand is an iterable, then its elements are
broken out and appended to the list individually:

The .append() method does not work that way! If an iterable is appended to a list with .append(), it is added as a single
object:

• a.extend(<iterable>) Extends a list with the objects from an iterable.

pg. 36
Yes, this is probably what you think it is. .extend() also adds to the end of a list, but the argument is expected to be an
iterable. The items in <iterable> are added individually:

In other words, .extend() behaves like the + operator. More precisely, since it modifies the list in place, it behaves like the
+= operator:

• a.insert(<index>, <obj>) Inserts an object into a list.


a.insert(<index>, <obj>) inserts object <obj> into list a at the specified <index>. Following the method call, a[<index>] is
<obj>, and the remaining list elements are pushed to the right:

• a.remove(<obj>) Removes an object from a list.


a.remove(<obj>) removes object <obj> from list a. If <obj> isn’t in a, an exception is raised:

• a.pop(index=-1) Removes an element from a list.


This method differs from .remove() in two ways:

• You specify the index of the item to remove, rather than the object itself.
• The method returns a value: the item that was removed.

pg. 37
a.pop() simply removes the last item in the list:

If the optional <index> parameter is specified, the item at that index is removed and returned. <index> may be negative, as
with string and list indexing:

<index> defaults to -1, so a.pop(-1) is equivalent to a.pop().

pg. 38
2.6 Python Tuples

Python provides another type that is an ordered collection of objects, called a tuple.

Pronunciation varies depending on whom you ask. Some pronounce it as though it were spelled “too-ple” (rhyming with
“Mott the Hoople”), and others as though it were spelled “tup-ple” (rhyming with “supple”). My inclination is the latter,
since it presumably derives from the same origin as “quintuple,” “sextuple,” “octuple,” and so on, and everyone I know
pronounces these latter as though they rhymed with “supple.”

Defining and Using Tuples

Tuples are identical to lists in all respects, except for the following properties:

• Tuples are defined by enclosing the elements in parentheses (()) instead of square brackets ([]).
• Tuples are immutable.
Here is a short example showing a tuple definition, indexing, and slicing:

Never fear! Our favorite string and list reversal mechanism works for tuples as well:

Everything you’ve learned about lists—they are ordered, they can contain arbitrary objects, they can be indexed and sliced,
they can be nested—is true of tuples as well. But they can’t be modified:

pg. 39
Why use a tuple instead of a list?

• Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to
be noticeable when the list or tuple is small.)
• Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life
of the program, using a tuple instead of a list guards against accidental modification.
• There is another Python data type that you will encounter shortly called a dictionary, which requires as one of its
components a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be.

In a Python REPL session, you can display the values of several objects simultaneously by entering them directly at the
>>> prompt, separated by commas:

Python displays the response in parentheses because it is implicitly interpreting the input as a tuple.

There is one peculiarity regarding tuple definition that you should be aware of. There is no ambiguity when defining an
empty tuple, nor one with two or more elements. Python knows you are defining a tuple:

But what happens when you try to define a tuple with one item:

pg. 40
Doh! Since parentheses are also used to define operator precedence in expressions, Python evaluates the expression (2) as
simply the integer 2 and creates an int object. To tell Python that you really want to define a singleton tuple, include a
trailing comma (,) just before the closing parenthesis:

You probably won’t need to define a singleton tuple often, but there has to be a way.

When you display a singleton tuple, Python includes the comma, to remind you that it’s a tuple:

Tuple Assignment, Packing, and Unpacking

As you have already seen above, a literal tuple containing several items can be assigned to a single object:

When this occurs, it is as though the items in the tuple have been “packed” into the object:

pg. 41
If that “packed” object is subsequently assigned to a new tuple, the individual items are “unpacked” into the objects in the
tuple:

When unpacking, the number of variables on the left must match the number of values in the tuple:

pg. 42
Packing and unpacking can be combined into one statement to make a compound assignment:

Again, the number of elements in the tuple on the left of the assignment must equal the number on the right:

Tasks:

pg. 43

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy