0% found this document useful (0 votes)
7 views37 pages

Python Lists and Data Structures Guide

This document covers application development using Python, focusing on lists, dictionaries, and string manipulation. It provides detailed explanations of list operations, including creation, indexing, concatenation, and methods for adding or removing elements. Additionally, it includes examples and projects to illustrate the concepts discussed.

Uploaded by

chittemrohitha16
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)
7 views37 pages

Python Lists and Data Structures Guide

This document covers application development using Python, focusing on lists, dictionaries, and string manipulation. It provides detailed explanations of list operations, including creation, indexing, concatenation, and methods for adding or removing elements. Additionally, it includes examples and projects to illustrate the concepts discussed.

Uploaded by

chittemrohitha16
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

APPLICATION DEVELOPMENT

USING
PYTHON
MODULE-2
CONTENTS
• Lists: The List Data Type, Working with Lists,
Augmented Assignment Operators, Methods, Example
Program: Magic 8 Ball with a List, List-like Types:
Strings and Tuples, References,

• Dictionaries and Structuring Data: The Dictionary


Data Type, Pretty Printing, Using Data Structures
to Model Real-World Things,

• Manipulating Strings: Working with Strings, Useful


String Methods, Project: Password Locker, Project:
Adding Bullets to Wiki Markup
CHAPTER 1-LISTS
• List datatype : collection of homogenous or
heterogenous values.

• It can contain values of all python valid


datatypes

• The vales should be enclosed within [


],separated by comma(,)

• The order in which the values are inserted ,will


be preserved.

• List is mutual datatype,(values can be modified)


Examples:
• >>> [10,20,30]
[10, 20, 30]
• >>> lst1=[10,20,30]
• >>> lst1
[10, 20, 30]
• >>> type(lst1)
<class 'list’>
• >>> id(lst1)
2521788515584 -ve index
-4 -3 -2 10 -1
20.5 (3+5j) ‘Hello
• >>> lst2=[10,20.5,3+5j,'hello'] ’
• >>> lst2 +ve index
0 1 2 3
[10, 20.5, (3+5j), 'hello']
• >>> lst2[0] Accessing elements in the inner
collection
10
� lst3=[10,20.5,3+5j,'hello']
• lst2[-4] � >>> lst3
10 [10, 20.5, (3+5j), 'hello']
• >>> lst2[2] � >>> lst3[3][0]
(3+5j) ‘h’
• >>> lst2[-1] � >>> lst4=[[50,60],10,'python']
'hello' � >>> lst4[0]

• >>> lst2[3] [50, 60]


� >>> lst4[0][0]
'hello’
50
• lst2[5]
� >>> lst4[0][1]
Traceback (most recent call 60
last):
File "<pyshell#26>", line LISTS are mutable
1, in <module> � >>> lst3[2]=200

lst2[5] � >>> lst3


[10, 20.5, 200, 'hello']
IndexError: list index out
List Concatenation (+)
• >>> lst3=lst3+[[20,30]] � >>> lst5+=[10]
• >>> lst3 � >>> lst5
[10, 20.5, 200, 'hello', [10]
[20, 30]] � >>> lst5+=[20.5]
• >>> lst3+=[3+5j] � >>> lst5
• >>> lst3 [10, 20.5]
[10, 20.5, 200, 'hello', � >>> lst5+=[3+5j]
[20, 30], (3+5j)]
� >>> lst5
• lst5=[ ]
[10, 20.5, (3+5j)]
• >>> lst5
� >>> lst5+=['hello']
[ ]
� >>> lst5
• >>> lst5+=10 [10, 20.5, (3+5j), 'hello']
Traceback (most recent call � >>> lst5+=[[10,20]]
last):
� >>> lst5
File "<pyshell#15>", line
1, in <module> [10, 20.5, (3+5j), 'hello', [10, 20]]
lst5+=10
List Replication(*)
• lst3=[20,3+5j,'hello']
• >>> lst3=lst3*2
• >>> lst3
[20, (3+5j), 'hello', 20, (3+5j), 'hello’]
• >>> lst3[2]
'hello'
• >>> lst3[5]
'hello’
• >>> lst3[2][0]
'h'
• >>> lst3[5][0]
'h'
SLICING(STRINGS)
Using +ve index � Using -ve index � Reversing string
• >>> name[0:3] � >>> len(name) � >>> name='python'
'pyt' 6 � >>> name[-1:-7:-1]
• >>> name[3] � >>> name[-6:-1:1] 'nohtyp’
'h' 'pytho' � >>> name[-1::-1]
• >>> name[:3] � >>> name[-6:0:1] 'nohtyp’
'pyt' ''
• >>> name[:3:1] � >>> name[-6:0] ACCESING CHARACTERS
'pyt’ '' � >>> name[::2]
• >>> name[::] � >>> name[-6:-1:-1] 'pto’
'python’ '' � >>> name[-1::-2]
• >>> � >>> name[-6:] 'nhy'
name[0:len(name): 'python’
1]
'python'
SLICING(LIST)
• >>> � >>> lst[::2]
lst=[10,20.5,3+5j,'python
',[10,20]] [10, (3+5j), [10, 20]]

• >>> len(lst)
5 � >>> lst[-1:-len(lst)-1:-1]
[[10, 20], 'python', (3+5j), 20.5,
10]
• >>> lst[:len(lst):]
[10, 20.5, (3+5j),
'python', [10, 20]] � >>> lst[::]
[10, 20.5, (3+5j), 'python', [10,
• >>> lst[1::] 20]]

[20.5, (3+5j), 'python',


[10, 20]] � >>> lst[2:4]
[(3+5j), 'python']
• >>> lst[:4:]
[10, 20.5, (3+5j),
Displaying elements of the
list
Using index( ) Method Using index( ) Method
Using index
� >>> � >>> [Link](10)
• >>> lst[0] lst=['cat','bat','rat', Traceback (most recent call
10 20,3+5j,[10,20]] last):
• >>> lst[-5] � >>> lst File "<pyshell#6>", line 1, in
10 ['cat', 'bat', 'rat', 20, <module>
(3+5j), [10, 20]]
• >>> lst[2] [Link](10)
� >>> [Link]('cat') ValueError: 10 is not in list
(3+5j)
0 � >>> [Link]([10,20])
• >>> lst[-3]
� >>> [Link]('rat') 5
(3+5j)
2 � >>> [Link]([10])
>>>
lst[4][0] � >>> [Link](3+5j) Traceback (most recent call
last):
10 4
File "<pyshell#8>", line 1, in
>>> lst[- <module>
1][0] [Link]([10])
ADDING VALUES TO THE LIST
USING +(CONCATINATION) USING +(CONCATINATION)

• >>> lst2=[10] � >>> list('hello')


• >>> lst2=lst2+[30] ['h', 'e', 'l', 'l', 'o']
• >>> lst2 � >>> lst2=lst2+list('hello')
[10, 30] � >>> lst2
• >>> lst2=lst2+30.5
[10, 30, 30.5, 'h', 'e', 'l', 'l', 'o’]
Traceback (most recent call last):
� >>> lst2=lst2+list(30.5)
File "<pyshell#3>", line 1, in <module>
lst2=lst2+30.5 Traceback (most recent call last):
TypeError: can only concatenate list (not File "<pyshell#12>", line 1, in
"float") to list <module>
• >>> lst2=lst2+[30.5] lst2=lst2+list(30.5)
• >>> lst2
TypeError: 'float' object is not
[10, 30, 30.5] iterable
USING append() and insert()
• >>> lst1=[10,20.5] Without using insert()
• >>> [Link]('hello') � >>> lst1
• >>> lst1 [10, 20.5, 'hello’]
[10, 20.5, 'hello’]

� >>> lst1[:1]+[3+5j]+lst1[2:]
• >>> [Link](2,3+5j)
[10, (3+5j), 'hello']
• >>> lst1
[10, 20.5, (3+5j), 'hello’]
• >>> [Link](3,[10,20])
• >>> lst1
[10, 20.5, 'hello', [10,
20]]
• >>> lst1=[10,20.5] NOTE:
• >>> id(lst1) � The append() and insert() methods are
2359063158272 list methods and can be called only on
list values, not on other values such
• >>> [Link]('hello') as strings or integers.
• >>> lst1 � >>> num=20
[10, 20.5, 'hello'] � >>> [Link](1,20)
• >>> id(lst1) Traceback (most recent call last):
2359063158272 File "<pyshell#9>", line 1, in <module>
• >>> [Link](2,4+7j) [Link](1,20)
• >>> lst1 AttributeError: 'int' object has no
attribute 'insert’
[10, 20.5, (4+7j), 'hello']
• >>> id(lst1)
� >>> str1='hello'
2359063158272
� >>> [Link](3,'y')

NOTE: Traceback (most recent call last):

• The return value of append() File "<pyshell#11>", line 1, in <module>


and insert() is None, so you [Link](3,'y')
definitely wouldn’t want to
store this as the new variable AttributeError: 'str' object has no
value. attribute 'insert'
Finding a Value in a List with the index()
Method
>>> lst1=[10,20,30.5,'pyhton']
>>> [Link](20)
1

>>> [Link]('pyhton’)
3

>>> [Link](5j)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
[Link](5j)
ValueError: 5j is not in list
Removing Values from Lists
Using del statement Using remove( ) method
• lst1=[10,20,30.5,’python’] � >>> lst1=[10,20.5,4+5j,'hello']
� >>> lst1
• del lst1[0] [10, 20.5, (4+5j), 'hello’]
• >>> lst1
[20, 30.5, ‘python’]
� >>> len(lst1)
4
• >>> len(lst1)
3
• >>> lst1 � >>> [Link](20.5)
[20, 30.5, ‘python’] � >>> lst1
[10, (4+5j), 'hello’]
• >>> lst1=[10,20.5,4+5j,'hello’]
� >>> len(lst1)
• >>> lst1 3
[10, 20.5, (4+5j), 'hello']
• >>> del lst1[[Link](10)] � >>> [Link](lst1[1])
• >>> lst1
� >>> lst1
[20.5, (4+5j), 'hello']
[10, 'hello']
Sorting the Values in a List
using sort()
>>> lst1=[20,4,8,10,30] � >>> lst1=['c','B','d','D','A']
>>> [Link]() � >>> [Link]()
>>> lst1 � >>> lst1
[4, 8, 10, 20, 30] ['A', 'B', 'D', 'c', 'd’]

>>> lst1=[10,20.5,15.6,34,25.6] � >>> lst1=['5','8','6','3']


>>> [Link]() � >>> [Link]()
>>> lst1 � >>> lst1

[10, 15.6, 20.5, 25.6, 34] ['3', '5', '6', ‘8’]

� >>> lst1=[20,12,'a','m','g']
>>>
lst1=['alpha','beta','delta','cre � >>> [Link]()
ta','jaquar','kent'] Traceback (most recent call last):
>>> [Link]() File "<pyshell#16>", line 1, in <module>
>>> lst1 [Link]()
['alpha', 'beta', 'creta', TypeError: '<' not supported between instances of
'delta', 'jaquar’, 'kent'] 'str' and 'int'
Note 1: You can also Note 2: If you need to sort the values in
regular alphabetical order, pass
pass True for the [Link] for the key keyword argument in
reverse keyword argument the sort() method call.
to have sort() sort the
values in reverse order � >>> lst1=['a','b','A','B','z','M']
� >>> [Link]()
� >>> lst1
>>> lst1=[23,45,38,7]
['A', 'B', 'M', 'a', 'b', 'z']
>>> [Link]()
>>> lst1 � >>> [Link](key=[Link])
� >>> lst1
[7, 23, 38, 45]
['A', 'a', 'B', 'b', 'M', ‘z’]
OR
>>> >>> [Link](key=[Link])
[Link](reverse=True) >>> lst1
>>> lst1 ['A', 'a', 'B', 'b', 'M', 'z']
Reversing the Values in a List with the
reverse() Method
>>> lst1
['A', 'a', 'B', 'b',
'M', 'z’]

>>> [Link]()
>>> lst1
['z', 'M', 'b', 'B',
'a', ‘A’]

>>>
lst1=[25,10,35,50,8]
>>> [Link]()
>>> lst1
[8, 50, 35, 10, 25]
Using for Loops with Lists
PROGRAM: Output:
enter number of animals5
n=int(input('enter number
enter 5 animal names
of animals'))
enter 1 animal name
print('enter',n,'animal lion
names') enter 2 animal name
animal_names=[ ] tiger
for i in range(n): enter 3 animal name
dog

print('enter',i+1,'animal enter 4 animal name


name’) cow
enter 5 animal name
a_name=input()
rabbit
['lion', 'tiger', 'dog', 'cow',
animal_names+=[a_name] 'rabbit']
WHILE LOOP FOR LIST
PROGRAM OUTPUT:

n=int(input('enter number of enter number of animals4


animals')) enter 4 animal names

print('enter',n,'animal names') enter 1 animal name


tiger
animal_names = []
enter 2 animal name
i=0 lion
while i<n: enter 3 animal name
rabbit
print('enter',i+1,'animal name') enter 4 animal name
aname = input() cow
animal_names = The cat names are:
animal_names + [aname] tiger
i+=1 lion
rabbit
cow
print('The cat names are:')
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: a value to look for in a list and the
list where it may be found.
• These expressions will evaluate to a Boolean value.

>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']


True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
PROGRAM: OUTPUT:

myPets = ['Zophie', 'Pooka', 'Fat- Enter a pet name:


tail'] Footfoot
print('Enter a pet name:') I do not have a pet named
name = input() Footfoot

if name not in myPets:


print('I do not have a pet
named ' + name)
else:
print(name + ' is my pet.')
Linear search
n=int(input('enter number of animals')) Output:

print('enter',n,'animal names') enter number of animals4


animal_names = [ ] enter 4 animal names
i=0 enter 1 animal name
flag=False
tiger
while i<n:
enter 2 animal name
print('enter',i+1,'animal name')
lion
aname = input()
enter 3 animal name
animal_names = animal_names + [aname]
elephant
i+=1
enter 4 animal name

cow
print('The animal names are:')
The animal names are:
print( animal_names)
['tiger', 'lion', 'elephant', 'cow']
print(‘enter your pet animal:')
enter your pet animal namecow
petanimal=input()

for animal in animal_names : cowpresent in the list

if animal==petanimal:

flag=True

break

if flag==True:

print(petanimal+'present in the list')

else:

print(petanimal+' not present in the list')


The Multiple Assignment
Trick Values of list to VARIABLES
� >>> list1=[20,36.5,'hello',5j]

LIST of values � >>> list1


[20, 36.5, 'hello', 5j]
to VARIABLES � >>> a,b,c,d=list1
>>> � >>> a

x,y,z=10,20,30 20
� >>> b
>>> x 36.5

10 � >>> c
'hello'
>>> y � >>> d

20 5j
� >>> a,b,c,d,e=list1
>>> z Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
30
a,b,c,d,e=list1
ValueError: not enough values to unpack (expected 5, got 4)
Using the enumerate() Function with
Lists
• Instead of using the range(len(someList)) technique with a
for loop to obtain the integer index of the items in the
list, you can call the enumerate() function instead.
• On each iteration of the loop, enumerate() will return two
values: the index of the item in the list, and the item in
the list itself.
• The enumerate() function is useful if you need both the
item and the
>>>
item’s index in the loop’s block.
pet_animals=['cat','cow','dog','sheep','g
oat']
>>> for index,item in
enumerate(pet_animals):
print("index", index," is having
animal:", item)

Output:
index 0 is having animal: cat
index 1 is having animal: cow
index 2 is having animal: dog
Functions in random module for list
Using [Link]( ) Using [Link]()
� The [Link]() function will reorder the
>>> import random items in a list. This function modifies the
list in place, rather than returning a new
>>>pet_animals=['cat','cow','dog','she list
ep','goat'] >>> import random
>>> [Link](pet_animals) >>>pet_animals=['cat','cow','dog','sheep','goa
t']
'dog’
>>> print(pet_animals)
>>> [Link](pet_animals) ['cat', 'cow', 'dog', 'sheep', 'goat']
'goat' >>> [Link](pet_animals)
>>> [Link](pet_animals) >>> print(pet_animals)
['goat', 'sheep', 'cat', 'dog', 'cow’]
'cow'
>>> id(pet_animals)
>>> [Link](pet_animals)
1820284294528
'cat' >>> [Link](pet_animals)
>>> print(pet_animals)
['sheep', 'goat', 'dog', 'cow', 'cat']
>>> id(pet_animals)
1820284294528
Magic 8 Ball with a List
PROGRAM: Output:
import random My reply is no
messages = ['It is certain’,
'It is decidedly so’,
'Yes definitely’, Yes definitely
'Reply hazy try again’,
'Ask again later’,
'Concentrate and ask again’,
'My reply is no','Outlook not so good’,
'Very doubtful']
print(messages[[Link](0, len(messages) -
1)])
Sequence Data Types
• The Python sequence data types include lists,
strings, range objects returned by range(), and
tuples

• Many of the things you can do with lists can also


be done with strings and other values of sequence
types: indexing; slicing; and using them with for
loops, with len(), and with the in and not in
operators.
Mutable and Immutable Data
• A list
Types
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,
� Examples: (on strings) � Proper way to modify(slicing and
>>> name="bangalore" concate)

>>> name[2] >>> name="bangalore"


'n' >>> name[2]
>>> name[2]='m' 'n’
Traceback (most recent call last): >>> name=name[0:2]+'m'+name[3:]
File "<pyshell#2>", line 1, in >>> name
<module>
'bamgalore’
name[2]='m'
>>> name[2]
TypeError: 'str' object does not
support item assignment 'm'
� Examples: LIST Example 3:
Example 1: >>> pet_animals=['cat','cow','sheep','goat']
>>>
>>> pet_animals=['cat','cow','sheep','goat'] pet_animals=pet_animals[:2]+['dog']+pet_animals[2:]
>>> pet_animals >>> pet_animals
['cat', 'cow', 'sheep', 'goat'] ['cat', 'cow', 'dog', 'sheep', 'goat']
>>> pet_animals[2] >>> pet_animals[2]
'sheep' 'dog’
>>> pet_animals[2]='bull'
>>> pet_animals Example 4:

['cat', 'cow', 'bull', 'goat’]


>>> pet_animals=[]
>>> pet_animals[2]
>>> pet_animals
'bull’
[]
>>> pet_animals.append('cat')
Example 2: >>> pet_animals
>>> ['cat']
pet_animals=pet_animals[0:2]+['bull']+pet_anim
als[3:] >>> pet_animals.append('dog')
>>> pet_animals >>> pet_animals

['cat', 'cow', 'bull', 'goat'] ['cat', 'dog']


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 ].
• The main way that tuples are different from lists is that
tuples, like strings,
Examples are immutable. Tuples cannot have
Examples(immutable)
their values modified,
>>> animals=() appended, or removed.
>>> animals=('cat','dog','tiger’)
>>> animals >>> type(animals)
() <class 'tuple'>
>>> animals=(10)
>>> animals
>>> animals
('cat', 'dog', 'tiger')
10
>>> animals[2]
>>> type(animals)
'tiger'
<class 'int'>
>>> animals=(10,)
>>> animals[2]='cow'
>>> animals Traceback (most recent call last):
(10,) File "<pyshell#3>", line 1, in <module>
>>> type(animals) animals[2]='cow'
<class 'tuple'> TypeError: 'tuple' object does not support item
assignment
Converting Types with the list() and tuple()
Functions
>>> >>> name="hello"
sample_list=[10,20.5,5j,'cat',
[10,20]] >>> type(name)
>>> type(sample_list) <class 'str’>
<class 'list'>
>>> str_lst=list(name)
>>> tuple(sample_list)
>>> str_lst
(10, 20.5, 5j, 'cat', [10,
20]) ['h', 'e', 'l', 'l', 'o']
>>> >>> str_tpl=tuple(name)
sample_tuple=tuple(sample_list
) >>> str_tpl
>>> sample_tuple
('h', 'e', 'l', 'l', 'o')
(10, 20.5, 5j, 'cat', [10,
20])
>>> sample_tuple[2]
5j
>>> len(sample_tuple)
5
>>> type(sample_tuple)
<class 'tuple'>
>>> num=10
References >>>
>>> name1="python"
>>> id(num) lst1=[10,20.5,3+5j,'he
140708846770224 >>> name2=name1 llo']
>>> num1=num >>> name1 is name2 >>> lst2=lst1
>>> num1
True >>> lst2
10
>>> name2 [10, 20.5, (3+5j),
>>> id(num1)
'hello']
140708846770224 'python'
>>> num1=20
>>> lst2 is lst1
>>> id(num1) >>> True
140708846770544
name2=name2[:2]+'R'+name2[2
>>> lst2[2]=700
>>> id(num)
:]
>>> lst2 is lst1
140708846770224 >>> name2
>>> num1 True
'pyRthon'
20 >>> lst1
>>> num >>> name2 is name1 [10, 20.5, 700,
10 False 'hello']
>>> num1 is num >>> lst2
False
>>> name1
[10, 20.5, 700,
>>> num1 is not num 'python' 'hello']
True
>>> id(lst1)
Passing References
• When a function is called, the values of the
arguments are copied to the parameter
variables.
• For lists and dictionaries a copy of the
reference is used for the parameter.
PROGRAM: Output:
def passingref(list2): list1 before calling method= [10, 20.5,
(3+7j)]
[Link]('hello')
list2= [10, 20.5, (3+7j), 'hello']
print("list2=",list2)
list1 after calling method= [10, 20.5,
(3+7j), 'hello']
list1=[10,20.5,3+7j]
print("list1 before calling
method=",list1)
passingref(list1)
print("list1 after calling
method=",list1) .
COPY and its types
• Copy operations are used to copy the contents of
one variable to another variable
• 3 types:
[Link] copy
[Link] copy
[Link] copy

General copy:
à Using = operator
à Syntax: Var2=var1
à It will copy the memory address of one variable to another variable
à Example: refer the references topic
Shallow copy
• Done by using copy( )
• Any modifications done with respect to the outer layer of
the collection datatype will not have impact on the other
collections.
• But any modifications done with respect to the inner
collection will have impact on each other.[because both
� will be pointing to
Example: >>>same inner collection]
list2[1]=777 >>> id(list2[3])
>>> >>> list2 1452426596544
list1=[10,20.5,3+5j,[50,60
]] [10, 777, (3+5j), [50, >>> id(list1[3])
60]]
>>> list2=[Link]() 1452426596544
>>> list1
>>> list2
[10, 20.5, (3+5j), [50, [10, 20.5, (3+5j), [50,
60]] 60]]
>>> list2 is list1 >>> list2[3][1]=600
False >>> list2
>>> id(list2) [10, 777, (3+5j), [50,
1452457923200 600]]
>>> id(list1) >>> list1
Deep copy
• Done by using [Link]( )
• Used to create separate copy of each and every
item present in one variable to another
variable
• To use deepcopy( ) import copy module
� Example >>> list1[1]=777
>>> import copy >>> list1
>>>
[10, 777, (3+3j), [50, 60]]
list1=[10,25.6,3+3j,[50,60]]
>>> list2=[Link](list1) >>> list2
>>> id(list2) [10, 25.6, (3+3j), [50, 60]]
2241877842688 >>> list2[3][0]=555
>>> id(list1) >>> list2
2241877841344 [10, 25.6, (3+3j), [555, 60]]
>>> list2
>>> list1
[10, 25.6, (3+3j), [50, 60]]
[10, 777, (3+3j), [50, 60]]
>>> list1
[10, 25.6, (3+3j), [50, 60]]

You might also like