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

python module 2

Uploaded by

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

python module 2

Uploaded by

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

INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

MODULE 2
CHAPTER 4: LISTS

1. The List Data Type


2. Working with Lists
3. Augmented Assignment Operators
4. Methods
5. Example Program: Magic 8 Ball with a List
6. List-like Types: Strings and Tuples
7. References

1. The List Data Type


Definition:
 A list is a value that contains multiple values in an ordered sequence.
Example: ['cat', 'bat', 'rat', 'elephant'].
 A list begins with an opening square bracket and ends with a closing one,[ ].
 Values inside the list are also called items and are separated with commas.

 In the above example, the spam variable contains one value, that is a list with multiple
values.
 The value [ ] is an empty list, that contains no values, similar to the empty string.

Getting Individual Values in a List with indexes.


 For a list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam.
 The Python code spam[0] would evaluate to 'cat', and spam[1] would evaluate to 'bat',
and so on.

AITM, Bhatkal Page 1


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

 The first value in the list is at index 0, the second value is at index 1, and the third value
is at index 2, and so on.
Example:

 The expression 'Hello ' + spam[0] evaluates to 'Hello ' + 'cat' because spam[0] evaluatesto
the string 'cat'. This expression in turn evaluates to the string value 'Hello cat'.

 If an index that exceeds the number of values in the list value then, python gives
IndexError. Indexes can be only integer values, not floats

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

 The first index i n d icates which list value to use, and the second indicates the
value within the list value. Ex, spam[0][1] prints 'bat', the second value in the first list.

AITM, Bhatkal Page 2


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Negative Indexes

 Negative integers can also be used for the index. The integer value -1 refers to the last
index in a list, the value -2 refers to the second-to-last index in a list, and so on.

Getting Sublists with Slices


 An index will get a single value from a list, a slice can get several values from a list,
in the form of a new list.
 A slice is typed between square brackets, like an index, but it has two integers
separated by a colon.
 Difference between indexes and slices.
o spam[2] is a list with an index (one integer).

o 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 (but will not include the value at the second index).

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

Getting a List’s Length with len()


AITM, Bhatkal Page 3
INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

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

Changing Values in a List with Indexes

 An index can also be used to change the value at that index.

 spam[1]=20 means , assign the value 20 at index ‘1’ in the list spam.
List Concatenation and List Replication
 The + operator can be used to combine two lists to create a new list, in the same
way it combines two strings into a new string value.

 The * operator can also be used with a list and an integer value to replicate the list.

Removing Values from Lists with del Statements

 The del statement will delete values at an index in a list.


 The del statement can also be used to delete a variable. After deleting if the variable is
used then it results in a NameError error, because the variable no longer exists.

 The del statement is mostly used to delete values from lists.


AITM, Bhatkal Page 4


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

2. Working with Listsi


i. Using while loop:
 Instead of using multiple, repetitive variables, One single variable that contains a
list value can be used.
 For Ex: The following program uses a single list and it can store any number of cats
that the user types in.
 Program: 

Output:

Using for Loops with Lists


A for loop repeats the code block once for each value in a list or list-like value.
Program:

AITM, Bhatkal Page 5


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Output:

 A common Python technique is to use range (len(someList)) with a for loop to iterate
over the indexes of a list.

 The code in the loop will access the index (as the variable i), the value at that index (as
supplies[i]) and range(len(supplies)) will iterate through all the indexes of supplies, no
matter how many items it contains.
The in and not in Operators
 To determine whether a value is or isn’t in a list, the in and not in operators can be used.

 The in and not in are used in expressions and connect two values:
o a value to look for in a list and
o the list where it may be found 
 These expressions will evaluate to a Boolean value.

 

AITM, Bhatkal Page 6


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

 The below program lets the user type in a pet name and then checks to see whether the
name is in a list of pets.
Program

Output

The Multiple Assignment Trick


 The multiple assignment trick is a shortcut that lets the user assign multiple variables
with the values in a list in one line of code.

 Instead of left-side program one could type the right-side program to assignment
multiple variables but the number of variables and the length of the list must be exactly
equal, or Python will give a ValueError:

3. Augmented Assignment Operators


 When assigning a value to a variable, the variable itself is used frequently.

 One shortcut is to use the augmented assignment operator += instead of using the
variable itself, as shown above. The below table shows the augment assignment
operators and their equivalents.
AITM, Bhatkal Page 7
INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

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

4. Methods
 A method is same as a function, except it is “called on” a value.
 The method part comes after the value, separated by a period.
 Each data type has its own set of methods. The list data type has several useful
methods for finding, adding, removing, andmanipulating values in a list.

i.Finding a Value in a List with the index() Method
 List values have an index() method that can be passed a value.

 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.


When there are duplicates of the value in the list, the index of its first appearance is
returned.
AITM, Bhatkal Page 8
INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

ii. Adding Values to Lists with the append() and insert() Methods

 To add new values to a list, the append() and insert() methods are used.
 The append() method call adds the argument to the end of the list.

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

 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.

iii. Removing Values from Lists with remove()


 The remove() method is passed the value to be removed from the list it is called on.

 Attempting to delete a value that does not exist in the list will result in a ValueError
error.
 If the value appears multiple times in the list, only the first instance of the value will
be removed.

AITM, Bhatkal Page 9


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

 The del statement is good to use when the index of the value to be removed from the
list is known. 
iv. 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.

 The True for the reverse keyword argument to have sort() sort the values in
reverse order.

 There are three things you should note about the sort() method.
o First, the sort() method sorts the list in place.
o Second, lists that have both number values and string values in them cannot
be sorted.

o Third, sort() uses “ASCIIbetical order(upper case)” rather than actual


alphabeticalorder(lower case) for sorting strings.

 To sort the values in regular alphabetical order, pass str.lower for the keykeyword
argument in the sort() method call.
AITM, Bhatkal Page 10
INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

5. Example Program: Magic 8 Ball with a List


 Instead of several lines of nearly identical elif statements, a single list can be created.

 The expression used as the index into messages is: random.randint (0, len(messages) -
1).
 This produces a random number to use for the index, regardless of the size of messages.

Exceptions to Indentation Rules in Python


 The amount of indentation for a line of code tells Python what block it is in.
 Lists can actually span several lines in the source code file. The indentation of these lines
do not matter; Python knows that until it sees the ending square bracket, the list is not
finished.

 We can also split up a single instruction across multiple lines using the \ line continuation
character at the end.

AITM, Bhatkal Page 11


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

6. List-like Types: Strings and Tuples


 Lists aren’t the only data types that represent ordered sequences of values.
 Example: Similar operations can be performed on strings: indexing; slicing; and
using them with for loops, with len(), and with the in and not in operators.

Mutable and Immutable Data Types


String

 A string is immutable: It cannot be changed. Trying to reassign a singlecharacter


in a string results in a TypeError error.

 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.

AITM, Bhatkal Page 12


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

List
A list value is a mutable data type: It can have values added, removed, or changed.

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 lis t value ([1, 2, 3]).

Figure: When eggs = [4, 5, 6] is executed, the contents of eggs are replaced with anew list
value.
To modify the original list in eggs to contain [4, 5, 6], the items have to be deleted first, then
the items are added.

AITM, Bhatkal Page 13


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

The Tuple Data Type


 The tuple data type is almost identical to the list data type, except in two ways.
 First, tuples are typed with parentheses, ( and ), instead of square brackets, [ and ].

 Second, they are immutable and their contents cannot be changed. Tuples cannot have
their values modified, appended, or removed.

 A single value in a tuple can be d indicate by placing a trailingcomma after the


value inside the parentheses.

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

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

AITM, Bhatkal Page 14


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

References
As , variables store strings and integer values.

 In the above example, the value of cheese is not altered. This is because spam and cheese
are different variables that store different values.
 But lists works differently. When a list is assigned to a variable, we are actually assigning
a list reference to the variable.
 A reference is a value that points to some bit of data, anda list reference is a value that
points to a list.

 When a list is created, its reference is assigned to the spam variable. But the next line
copies only the list reference in spam to cheese, not the list value itself. This means the
values stored in spam and cheese now both refer to the same list.
 There is only one underlying list because the list itself was never actually copied.
 So when we modify the first element of cheese, we are modifying the same list that spam
refers to.
 List variables don’t actually contain lists—they contain references to lists.

AITM, Bhatkal Page 15


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Figure: spam = [0, 1, 2, 3, 4, 5] stores a reference to a list, not the actual list.

The reference in spam is copied to cheese. Only a new reference was created andstored in
cheese, not a new list.

Figure: spam = cheese copies the reference, not the list

When we alter the list that cheese refers to, the list that spam refers to is also changed,because
both cheese and spam refer to the same list.

Figure: cheese[1] = 'Hello!' modifies the list that both variables refer to

 Variables will contain references to list values rather than list values themselves.

AITM, Bhatkal Page 16


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

But for strings and integer values, variables will contain the string or integer value.
 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.
Passing References

 References are particularly important for understanding how arguments get passed to
functions.
 When a function is called, the values of the arguments are copied to the parameter
variables.
Program Output

 When eggs() is called, a return value is not used to assign a new value to spam.
 Even though spam and someParameter contain separate references, they both refer to the
same list.

 This is why the append('Hello') method call inside the function affects thelist even after
the function call has returned.
The copy Module’s copy() and deepcopy() Functions
 If the function modifies the list or dictionary that is passed, one may not want these
changes in the original list or dictionary value.
 For this, Python provides a module named copy that provides both the copy() and
deepcopy() functions.
 copy(), can be used to make a duplicate copy of a mutable value like a list or
dictionary, not just a copy of a reference.
 Now the spam and cheese variables refer to separate lists, which is why only the list
in cheese is modified when you assign 42 at index 1.

AITM, Bhatkal Page 17


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

 The reference ID numbers are no longer the same for both variables because the
variables refer to independent lists.

Figure: cheese = copy.copy(spam) creates a second list that can be modified independently of
the first.

>>> import copy


>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
Output: ['A', 'B', 'C', 'D']
>>> cheese
Output: ['A', 42, 'C', 'D']

copy function
>>> import copy
>>> old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> new_list = copy.copy(old_list)
>>> old_list[1][0] = 'BB'
>>> print("Old list:", old_list)
>>> print("New list:", new_list)
>>> print(id(old_list))
>>> print(id(new_list))

AITM, Bhatkal Page 18


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Output:
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
1498111334272
1498110961152

deepcopy() Function
>>> import copy
>>> old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> new_list = copy.deepcopy(old_list)
>>> old_list[1][0] = 'BB'
>>> print("Old list:", old_list)
>>> print("New list:", new_list)
>>> print(id(old_list))
>>> print(id(new_list))

Output
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
1498111298880
1498111336064

AITM, Bhatkal Page 19


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

CHAPTER 5: DICTIONARIES AND STRUCTURING DATA

1. The Dictionary Data Type

2. Pretty Printing

3. Using Data Structures to Model Real-World Things.

2.1 The Dictionary Data Type


 A dictionary is a collection of many values.

 Indexes for dictionaries can use many different data types, not just integers.

 Indexes for dictionaries are called keys, and a key with its associated value is called a
key-value pair.

 A dictionary is typed with braces, { }.


Example:

 The above example assigns a dictionary to the myCat variable. This dictionary’s keys are
'size', 'color', and 'disposition'. The values for these keys are 'fat', 'gray', and 'loud',
respectively. The values can be accessed through their keys:

 Dictionaries can still use integer values as keys, but they do not have to start at 0 and can
be any number.

Dictionaries vs. Lists


 Unlike lists, items in dictionaries are unordered.
 The first item in a list named spam would be spam[0]. But there is no “first” item in a
dictionary.

AITM, Bhatkal Page 20


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

 Trying to access a key that does not exist in a dictionary will result in a KeyError
error message, much like a list’s “out-of-range” IndexError error message.

Ex: To store data about friends’ birthdays, We can use a dictionary with the names as keys
and the birthdays as values.
Program:

AITM, Bhatkal Page 21


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Output:

Program Flow:
 An initial dictionary is created and it is stored in birthdays.
 If the name is in the dictionary, associated value is accessed using square brackets;if not,
the name is added to the dictionary using the same square bracket syntax combined with
the assignment operator.

Difference between lists and dictionaries:

LISTS DICTIONARY

An ordered collection of items. An unordered collection of data in a key:value


pair form.

Declared using [ ] square brackets. Declared using { } curly braces.

Ordered: Items have a defined order. Unordered: Items do not have a defined order.

Items are accessed using index, starting with 0. Values are accessed using keys.

Mutable: Items can be modified after creation. Mutable: Values can be modified, keys cannot.

Allows duplicate items. Does not allow duplicate keys. However, values
can be duplicated.

Functions: append( ), remove( ), pop( ), sort( ), etc. Functions: keys( ), values( ), items( ) etc.

AITM, Bhatkal Page 22


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

\The keys(), values(), and items() Methods

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

Example:

 A for loop can iterate over the keys, values, or key-value pairs in a dictionary by using
keys(), values(), and items() methods.
 The values returned by the items() method are tuples of the key and value.

 To get a true list from one of these methods, pass its list-like return value to the list()
function.

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

AITM, Bhatkal Page 23


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Checking Whether a Key or Value Exists in a Dictionary

The in and not in operators can be used to see whether a certain key or value exists in a
dictionary

The get() Method


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

The setdefault() Method


 The setdefault( ) method is used to set a value in a dictionary for a certain key only if
that key does not already have a value.


 The setdefault() method offers a way to do this in one line of code.
 Setdeafault() takes 2 arguments:
o The first argument is the key to check for, and
o The second argument is the value to set at that key if the key does not exist.
AITM, Bhatkal Page 24
INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

 If the key does exist, the setdefault() method returns the key’s value.
Example:

 The first time setdefault() is called, the dictionary in spam changes to {'color': 'black',
'age': 5, 'name': 'Pooka'}.

 The method returns the value 'black' because this is now the value set for the key 'color'.

 When spam.setdefault('color', 'white') is called next, the value for that key is not changed
to 'white’ because spam already has a key named 'color'.

Program: Program that counts the number of occurrences of each letter in a string.

 The program loops over each character in the message variable’s string, counting how
often each character appears.
 The setdefault() method call ensures that the key is in the count dictionary (with a default
value of 0), so the program doesn’t throw a KeyError error when count[character] =
count[character] + 1 is executed.
Output:

AITM, Bhatkal Page 25


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

2. Pretty Printing

 Importing pprint module will provide access to the pprint() and pformat() functions that
will “pretty print” a dictionary’s values.

 This is helpful when we want a cleaner display of the items in a dictionary than what
print() provides and also it is helpful when the dictionary itself contains nested lists or
dictionaries..
Program: counts the number of occurrences of each letter in a string (Using pprint)

Output:

AITM, Bhatkal Page 26


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

3. Using Data Structures to Model Real-World Things

A Tic-Tac-Toe Board

A tic-tac-toe board looks like a large hash symbol (#) with nine slots that can each contain an
X, an O, or a blank. To represent the board with a dictionary, we can assign each slot a string-
value key as shown in below figure.

Figure: The slots of a tic-tac-toe board with their corresponding keys

 String values can be used to represent what’s in each slot on the board: 'X', 'O', or ' ' (a
space character).
 To store nine strings. We can use a dictionary of values for this.
 The string value with the key 'top-R' can represent the top-right
corner,
 The string value with the key 'low-L' can represent the bottom-left
corner,
 The string value with the key 'mid-M' can represent the middle,
and so on.
 Store this board-as-a-dictionary in a variable named theBoard.

AITM, Bhatkal Page 27


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

 The data structure in theBoard above represents tic-tac-toe board in the below Figure

Figure: Player O wins.

 The player sees only what is printed to the screen, not the contents of variables.
Program:

Output:

AITM, Bhatkal Page 28


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Program

Output:

Program: To allows the players to enter their moves.


AITM, Bhatkal Page 29


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Output:

AITM, Bhatkal Page 30


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Nested Dictionaries and Lists

 It is possible to have program that contains dictionaries and lists which in turn
contain otherdictionaries and lists.
 Lists are useful to contain an ordered series of values, and dictionaries are useful for
associating keys with values.
Program: which contains nested dictionaries in order to see who is bringing what to apicnic

 Inside the totalBrought() function, the for loop iterates over the key value pairs in
guests 1.
 Inside the loop, the string of the guest’s name is assigned to k, and the dictionary of
picnic items they’re bringing is assigned to v.
 If the item parameter exists as a key in this dictionary, it’s value (the quantity) is
added to numBrought 2.
 If it does not exist as a key, the get() method returns 0 to be added to numBrought.
Output:

AITM, Bhatkal Page 31


INTODUCTION TO PYTHON PROGRAMMING- BPLCK105B/205B Module 2

Exercise Programs:

Write a function that takes a list value as an argument and returns a string with all the items
separated by a comma and a space, with and inserted before the last item.

Lab Programs:
3 and 4.

AITM, Bhatkal Page 32

You might also like