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

Py (MODULE 2) (Chapter1)

Uploaded by

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

Py (MODULE 2) (Chapter1)

Uploaded by

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

MODULE 2 BY- MIS.

ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
CHAPTER 1
[1.1THE LIST DATA TYPE]
• A list is a value that contains multiple values in an ordered sequence.
• A list begins with an opening square bracket and ends with a closing square bracket,
[].
• Values inside the list are also called items.
• Items are separated with commas (that is, they are comma-delimited).
• The value [ ] is an empty list that contains no values, similar to ‘ ’, the empty string.
•it is considered as Mutable datatype because list supoort all kind of modification.
•Syntax—
var=[val1,val2,val3,…………….,valn]

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Example— (Lists can also contain other list values)
>>> [1,2,3,'python']
[1, 2, 3, 'python']
Example—
>>> ['hello',3+5j,2.2,1]
>>> p=[1,2,3,4,[5,6,7,8]]
['hello', 3+5j, 2.2, 1]
1.1.1 Getting Individual Values in a List with Indexes—
>>> p[4]
l=['sunday','python',1,2.3,True,3+5j]
[5, 6, 7, 8]
>>> l[2] >>> p[2]
1 3
>>> l[4]
PREPARED BY- MIS.ITISHREE BARIK
True
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.2 INDEXING
•Fetching the element as per their index value is known as indexing.
•There are 2 types of indexing—
1. Positive indexing
2. Negative indexing
•Positive indexing always starts from ‘0’ & goes on.
•It always starts from left to right.
•Negative indexing always starts from ‘-1’.
•It always starts from right to left.

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Example—
s=['cat','bat','rat','elephant']
>>> s[-1]
'elephant'
>>> s[-3]
'bat‘
>>>'the '+s[-1]+'is afraid of the'+s[-3]+'.'
'the elephant is afraid of the bat.'

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.3 GETTING SUB LISTS WITH SLICES
Just as an index can 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.
In a slice, the first integer is the index where the slice starts & the second integer is
the index where the slice ends.

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Examples: >>> s = ['cat', 'bat', 'rat', 'elephant']
>>> s[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> s[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
• As a shortcut, you can leave out one or both of the indexes on either side of the colon in the slice.
• 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.
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Examples:
>>> s= ['cat', 'bat', 'rat', 'elephant']
>>> s[:2]
['cat', 'bat']
>>> s[1:]
['bat', 'rat', 'elephant']
>>> s[:]
['cat', 'bat', 'rat', 'elephant']
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.1.5 GETTING A LIST’S LENGTH WITH LEN()

The len() function will return the number of values that are in a list value passed to
it. Example:
>>> s = ['cat', 'dog', 'moose']
>>> len(s)
3
1.1.6 Changing Values in a List with Indexes
Use an index of a list to change the value at that index.
For example—
s[1] = ‘TIGER’ means “Assign the value at index 1 in the list s to the string ' TIGER
'.”
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Examples:
>>> s = ['cat', 'bat', 'rat', 'elephant']
>>> s[1] = ‘TIGER'
>>> s ['cat', ' TIGER ', 'rat', 'elephant']
>>> s[2] = s[1]
>>> s ['cat', ' TIGER ', ' TIGER ', 'elephant']
>>> s[-1] = 12345
>>> s ['cat', ' TIGER ', ' TIGER ', 12345]
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.1.7 LIST CONCATENATION AND LIST REPLICATION

The + operator can combine two lists to create a new list value 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.
Examples –
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
PREPARED BY- MIS.ITISHREE BARIK
>>> s = [1, 2, 3] ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.3 USING FOR LOOPS WITH LISTS

• A for loop repeats the code block once for each value in a list or list-like value.
Example 1:
for i in [0, 1, 2, 3]:
print(i)
Output: 0
1
2
3

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Example 2:
supplies = ['pens', 'staplers', ‘markers', 'binders']
for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
Output—
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: markers
Index 3 in supplies is: binders
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.4 THE IN AND NOT IN OPERATORS
• You can determine whether a value is or isn’t in a list with the in and not in operators.
• Like other operators, in and not in are used in expressions and connect two values:
1. a value to look for in a list
2. the list where it may be found.
Example 1:
>>> 'howdy' in ['hello', 'hi', 'howdy', 'hurrah']
True
>>> spam = ['hello', 'hi', 'howdy', ‘hurrah']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
EXAMPLE-2

myPets = ['kajol', 'johnny', 'tofan'] Output—


print('Enter a pet name:')
name = input()
if name not in myPets: Enter a pet name:
kajol
print('I do not have a pet named ' + name) kajol is my pet.
else:
print(name + ' is my pet.')

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.5 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.
Examples:
>>> cat = ['fat', 'black', ‘ZooZoo']
>>> size = cat[0]
>>> color = cat[1]
>>> name = cat[2]
you could type this line of code:
>>> cat = ['fat', 'black', 'ZooZoo']
>>> size, color, name = cat
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.6 AUGMENTED ASSIGNMENT OPERATORS

Examples:
>>> spam = 42
>>> spam = spam + 1
>>> spam
43
Replace With >>> spam = 42
>>> spam += 1
>>> spam
43
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
The augmented assignment operators for the +, -, *, /, and % operators

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
• The += operator can also do string and list concatenation, and the *= operator can do string and
list replication.
• Example –
>>> spam = 'Hello'
>>> spam += ' world!'
>>> spam
'Hello world!‘
>>> bacon = ['Zophie']
>>> bacon *= 3
>>> bacon
['Zophie', 'Zophie', 'Zophie']
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.7 LIST METHODS

• index
• append
• insert
• remove
• sort
1.7.1 index() - Finding a Value in a List with the index() Method
Example: --
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.7.2 append() - Adding Values to Lists with the append() Method.
Example:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append(‘rat')
>>> spam ['cat', 'dog', 'bat', ‘rat']
1.7.3 insert() - Adding Values to Lists with the insert() Method.
Example:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'rat')
>>> spam ['cat', 'rat', 'dog', 'bat']
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
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.
Example—
>>> eggs = 'hello‘
>>> eggs.append('world')
AttributeError: 'str' object has no attribute 'append‘
>>> bacon = 42
>>> bacon.insert(1, 'world')
AttributeError: 'int' object has no attribute 'insert'
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.7.4 remove() - Removing Values from Lists with remove()
Examples—
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam ['cat', 'rat', 'elephant']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('chicken')
ValueError: list.remove(x): x not in list
>>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
>>> spam.remove('cat')
>>> spam ['bat', 'rat', 'cat', 'hat', 'cat']
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.7.5 SORT()

• The sort() method is one of the ways you can sort a list in Python.
• When using sort(), you sort a list in-place.
• This means that the original list is directly modified. Specifially, the original order of elements is altered
Example— Output--

# a list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

[3, 7, 8, 10, 11, 22, 33, 54, 100


#sort list in-place in ascending order
my_numbers.sort()

#print modified list


print(my_numbers)
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.7.5.1 SORT THE VALUES IN REVERSE ORDER

• You can also pass True for the reverse keyword argument to have sort() sort the values in reverse
order.
Example— Output—
# a list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]
[100, 54, 33, 22, 11, 10, 8, 7, 3]
#sort list in-place in descending order
my_numbers.sort(reverse=True)

#print modified list


print(my_numbers)
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Three things to know about sorting
1. The sort() method sorts the list in place; don’t try to capture the return value by writing
code like spam = spam.sort().
2. You cannot sort lists that have both number values and string values in them, since Python
doesn’t know how to compare these values.
3. Sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting strings.
This means uppercase letters come before lowercase letters.
Example:
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> spam.sort()
TypeError: unorderable types: str() < int()

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
EXAMPLE PROGRAM: MAGIC 8 BALL WITHOUT A LIST

import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later' PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no' what do you ask of me?4
elif answerNumber == 8: Outlook not so good
return 'Outlook not so good'
elif answerNumber == 9:
return 'Very doubtful'
r=random.randint(1,9)
x=getAnswer(r)
int(input("what do you ask of me?"))
print(x)
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
MAGIC 8 BALL WITH A LIST

import random
messages = ['It is certain','It is decidedly so','Yes definitely','Reply hazy try again',
'Ask again later','Concentrate and ask again','My reply is no','Outlook not so good',
'Very doubtful']
question=int(input("enter to shake the magic 8 ball "))
enter to shake the magic 8 ball
while question:
Very doubtful
print(random.choice(messages)) press enter to shake the magic ba
question=int(input("press enter to shake the magic ball:")) It is decidedly so
press enter to shake the magic ba
print("") It is certain
press enter to shake the magic ba
Outlook not so good
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
press enter to shake the magic b
1.9 LIST-LIKE TYPES: STRINGS AND TUPLES

• Lists aren’t the only data types that represent ordered sequences of values.
• For example, strings and lists are actually similar, if you consider a string to be 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.
Example—
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
>>> name[0:4]
'Zoph‘
>>> 'Zo' in name Output—
True
>>> 'z' in name
***z***
False ***o***
>>> 'p' not in name ***p***
***h***
False ***i***
>>> for i in name: ***e***
print('* * * ' + i + ' * * *’)
PREPARED BY- MIS.ITISHREE BARIK
ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.10 MUTABLE AND IMMUTABLE DATA TYPES

• But lists and strings are different in an important way.


• A list value is a mutable data type: It can have values added, removed, or changed.
• However, a string is immutable: It cannot be changed.
• Trying to reassign a single character in a string results in a TypeError error.
Example –
>>> name = 'Zophie a cat‘
>>> name[7] = 'the‘
TypeError: 'str' object does not support item assignment 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.

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.11 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 ].
Tuples are different from lists is that tuples, like strings, are immutable (Tuples
cannot have their values modified, appended, or removed).
Example—
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
TypeError: 'tuple' object does not support item assignment

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
If you have only one value in your tuple, you can indicate this by placing a trailing
comma after the value inside the parentheses.
>>> type(('hello',))
<class ‘tuple’>
>>> type 'hello‘
<class ‘str’>
• Otherwise, Python will think you’ve just typed a value inside regular parentheses.
• The comma is what lets Python know this is a tuple value.

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.12 CONVERTING TYPES WITH THE LIST() AND
TUPLE() FUNCTIONS
Example—
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
1.13 REFERENCES (EXAMPLE 1- ASSIGNING VALUES TO
VARIABLES):

Example 1:
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
100

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Example 2 –
assign a list to a variable
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
>>> cheese[1] = ‘Hello!’
>>> spam [0, 'Hello!', 2, 3, 4, 5]
>>> cheese [0, 'Hello!', 2, 3, 4, 5]

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
THE COPY MODULE’S COPY() AND DEEPCOPY()
FUNCTIONS
• Python provides a module named copy that provides both the copy() and
deepcopy() functions.
• The first of these, copy.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.
• If the list you need to copy contains lists, then use the copy.deepcopy() function
instead of copy.copy(). The deepcopy() function will copy these inner lists as well.

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
EXAMPLE 1:

Copy:
a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a [[1, 2, 3], [4, 5, 6]]
>>> b [[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a [[1, 10, 3], [4, 5, 6]]
>>> b # b changes too -> Not a deepcopy. [[1, 10, 3], [4, 5, 6]]

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Deep Copy:
>>> import copy
>>> b = copy.deepcopy(a)
>>> a [[1, 10, 3], [4, 5, 6]]
>>> b [[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a [[1, 9, 3], [4, 5, 6]]
>>> b # b doesn't change -> Deep Copy [[1, 10, 3], [4, 5, 6]]

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Example 2—
>>>import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam ['A', 'B', 'C', 'D']
>>> cheese ['A', 42, 'C', 'D']

PREPARED BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT

You might also like