0% found this document useful (0 votes)
1 views20 pages

Chapter-4 Notes

This document provides an overview of lists and tuples in Python, detailing their characteristics, methods, and differences. It explains how to manipulate lists using indexing, slicing, and various methods like append(), insert(), and remove(). Additionally, it compares mutable lists with immutable tuples, highlighting their use cases and conversion functions.

Uploaded by

pranavbadagi10
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)
1 views20 pages

Chapter-4 Notes

This document provides an overview of lists and tuples in Python, detailing their characteristics, methods, and differences. It explains how to manipulate lists using indexing, slicing, and various methods like append(), insert(), and remove(). Additionally, it compares mutable lists with immutable tuples, highlighting their use cases and conversion functions.

Uploaded by

pranavbadagi10
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

MODULE -2: CHAPTER – 4

LISTS AND TUPLES

List is a datatype which contains multiple values in an ordered sequence.


List makes easier to handle large amounts of data.
Lists themselves can contain other lists.

Values inside the list are also called items. Items are separated with commas

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

The value [] is an empty list that contains no values.

Getting Individual Values in a List with Indexes:

The integer inside the square brackets that follows the list is called an
index. The first value in the list is at index 0, the second value is at index
1, the third value is at index 2, and so on.

1
Python will give you an IndexError error message if you use an index that
exceeds the number of values in your list value.

Indexes can be only integer values, not floats. The following example will cause
a TypeError error:

Lists can also contain other list values. The values in these lists of lists can be
accessed using multiple indexes.

If you only use one index, the program will print the full list value at that index.

2
Negative Indexes

Getting Subsists with Slices


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

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


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

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

As a shortcut, you can leave out one or both of the indexes on either side
of the colon in the slice

3
List’s Length with len()

The len() function will return the number of values that are in a list value
passed to it.

Changing Values in a List with Indexes

List Concatenation and List Replication


The + operator can combine two lists to create a new list.
The * operator can also be used with a list and an integer value to replicate the
list.

4
Removing Values from Lists with del Statements

The del statement will delete values at an index in a list. All of the values in the
list after the deleted value will be moved up one index.

If you try to use the variable after deleting it, you will get a NameError error
because the variable no longer exists.

Working with Lists

Instead of using multiple, repetitive variables, you can use a single variable that
contains a list value.

5
Output:

Using for Loops with Lists

A common Python technique is to use range(len(someList)) with a for loop to


iterate over the indexes of a list. For example,

6
Using range(len(supplies)) in for loop is handy because the code in the loop can
access the index (as the variable i) and the value at that index (as supplies[i]).
Best of all, range(len(supplies)) will iterate through all the indexes of supplies,
no matter how many items it contains.

The in and not in Operators

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

Example:

7
The Multiple Assignment Trick
The multiple assignment trick is a shortcut that lets you assign multiple
variables with the values in a list in one line of code.

Note : The number of variables and the length of the list must be exactly equal,
or Python will give you a ValueError:

Augmented Assignment Operators

As a shortcut, you can use the augmented assignment operator += to do


the same thing:

8
The += operator can also do string and list concatenation, and the *= operator
can do string and list replication.

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

For example, if a list value were stored in spam, you would call the index()
list method on that list like [Link]('hello').
The method part comes after the list, separated by a period.

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


List values have an index() method that can be passed a value, and if that
value exists in the list, the index of the value is returned. If the value isn’t
in the list, then Python produces a ValueError error.

9
Adding Values to Lists with the append() and insert() Methods
append() method call adds the argument to the end of the list.

Output:

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

Output:

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

10
Removing Values from Lists with remove()
The remove() method is passed the value to be removed from the list it is
called on.

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

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


Lists of number values or lists of strings can be sorted with the sort() method

11
You can also pass True for the reverse keyword argument to have sort() sort
the values in reverse order.

Three things you should note about the sort() method.

First, the sort() method sorts the list in place; don’t try to capture the return
value by writing code like spam = [Link]().
Second, you cannot sort lists that have both number values and string values in
them.

Third, sort() uses “ASCIIbetical order” rather than actual alphabetical order for
sorting strings. This means uppercase letters come before lowercase letters.

12
Example Program: Magic 8 Ball with a List

Exceptions to Indentation Rules in Python

Split up a single instruction across multiple lines using the \ line continuation
character at the end. Think of \ as saying, “This instruction continues on the
next line.” The indentation on the line after a \ line continuation is not
significant.

13
Strings and Tuples

String is a “list” of single text characters.


Many of the things you can do with lists can also be done with strings:
indexing; slicing; and using them with for loops, with len(), and with the in and
not in operators.

Mutable and Immutable Data Types

Difference between lists and strings:


A list value is a mutable data type: We can add, remove, or change values in it.
A string is immutable: It cannot be changed. Trying to reassign a single
character in a string results in a TypeError error.

14
The proper way to “mutate” a string is to use slicing and concatenation to build
a new string by copying from parts of the old string.

Although a list value is mutable, the second line in the following code does not
modify the list eggs:

The list value in eggs isn’t being changed here; rather, an entirely new and
different list value ([4, 5, 6]) is overwriting the old list value ([1, 2, 3]) as shown
below.

If you wanted to actually modify the original list in eggs to contain [4, 5, 6], you
would have to do something like this:

15
The Tuple Data Type

The tuple data type is almost identical to the list data type. except in two ways.
First, tuples are typed with parentheses.
Second, are immutable : their values cannot be modified, appended, or
removed.

If there is only one value in a tuple, you can indicate this by placing a trailing
comma after the value inside the parentheses. The comma is what lets Python
know this is a tuple value.

Advantages of Tuples:
• If you need an ordered sequence of values that never changes, use a tuple.
• A second benefit of using tuples instead of lists is that, because they are
immutable and their contents don’t change, Python can implement some
optimizations that make code using tuples slightly faster than code using
lists.

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

Just like how str(42) will return '42', the functions list() and tuple() will return
list and tuple versions of the values passed to them.

Converting a tuple to a list is handy if you need a mutable version of a tuple


value.

References

You assign 42 to the spam variable, and then you copy the value in spam and
assign it to the variable cheese. When you later change the value in spam to
100, this doesn’t affect the value in cheese. This is because spam and cheese
are different variables that store different values.

But lists don’t work this way. When you assign a list to a variable, you are
actually assigning a list reference to the variable.
A reference is a value that points to some bit of data, and
A list reference is a value that points to a list.

Example:

17
Python uses references whenever variables must store values of mutable data
types, such as lists or dictionaries. For values of immutable data types such as
strings, integers, or tuples, Python variables will store the value itself.

18
Passing References
When a function is called, the values of the arguments are copied to the
parameter variables. For lists, a copy of the reference is used for the
parameter.

Notice that when eggs() is called, a return value is not used to assign a new
value to spam. Instead, it modifies the list in place, directly.

Output:

The copy Module’s copy() and deepcopy() Functions

Python provides a module named copy that provides the copy() and deepcopy()
functions.
[Link](), can be used to make a duplicate copy of a mutable value like a list
or dictionary, not just a copy of a reference.

If the list you need to copy contains lists, then use the [Link]().
The deepcopy() function will copy these inner lists as well.

19
Practice Questions

1. What is []?
2. How would you assign the value 'hello' as the third value in a list stored
in a variable named spam? (Assume spam contains [2, 4, 6, 8, 10].)

For the following three questions, let’s say spam contains the list ['a', 'b', 'c',
'd'].
3. What does spam[int('3' * 2) / 11] evaluate to?
4. What does spam[-1] evaluate to?
5. What does spam[:2] evaluate to?

For the following three questions, let’s say bacon contains the list
[3.14, 'cat', 11, 'cat', True].
6. What does [Link]('cat') evaluate to?
7. What does [Link](99) make the list value in bacon look like?
8. What does [Link]('cat') make the list value in bacon look like?
9. What are the operators for list concatenation and list replication?
10. What is the difference between the append() and insert() list methods?
11. What are two ways to remove values from a list?
12. Name a few ways that list values are similar to string values.
13. What is the difference between lists and tuples?
14. How do you type the tuple value that has just the integer value 42 in it?
15. How can you get the tuple form of a list value? How can you get the list
form of a tuple value?
16. Variables that “contain” list values don’t actually contain lists directly.
What do they contain instead?
17. What is the difference between [Link]() and [Link]()?

20

You might also like