SlideShare a Scribd company logo
Lists, Dictionaries and structuring Data,
Manipulating strings
MODULE-
2
Topics Include
1. Lists 2. Dictionaries and
Structuring Data
3. Manipulating
Strings
a. The List Data Type, a. The Dictionary Data
type,
a. Working with Strings,
b. Working with Lists, b. Pretty Printing, b. Useful String
Methods,
c. Augmented
Assignment Operators,
c. Using Data Structures
to Model Real-World
Things
c. Project: Password
Locker,
d. Methods, d. Project: Adding
Bullets to Wiki Markup
e. Example Program:
Magic 8 Ball with a List,
f. List-like Types: Strings
and Tuples.
Objectives
● Explanation of what a list is.
● Create and index lists of simple values.
● Change the values of individual elements.
● Append values to an existing list.
● Reorder and slice list elements.
● List Concatenation and Replication.
● Multiple assignment Trick operator.
● Augmented assignment operators.
CHAPTER-4
LISTS
Chapter 4: Lists
● The list data type:
✔ A list is a value that contains multiple values in an ordered sequence.
Eg: ['cat', 'bat', 'rat', 'elephant'].
✔ Just as string values are typed with quote characters to mark where the
string begins and ends, 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
Hands-on with lists:
1. Typing on the console and observing the outputs:
>>> [1,2,3]
[1,2,3]
>>> ['cat', 'bat', 'rat', 'elephant']
['cat', 'bat', 'rat', 'elephant']
>>> ['hello', 3.1415, True, None, 42]
['hello', 3.1415, True, None, 42]
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
Getting Individual Values in a List with Indexes:
Let us consider a list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam.
>>> 'Hello ' + spam[0]
'Hello cat‘
• Errors with List:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last): File "<pyshell#9>", line 1,
in <module>
spam[10000] IndexError: list index out of range
Integer values are accepted in lists, floating values are
not accepted
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1]
'bat‘
>>> spam[1.0]
Traceback (most recent call last): File "<pyshell#13>",
line 1, in <module>
spam[1.0] TypeError: list indices must be integers, not float
>>> spam[int(1.0)]
'bat'
Lists can also contain other list values. The values in these lists of lists can be accessed using multiple
indexes
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0]
['cat', 'bat']
>>> spam[0][1]
'bat‘
>>> spam[1][4]
50
Negative Indexes
● 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.
Enter the following into the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
‘elephant’
>>> spam[-3]
‘bat’
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.‘
'The elephant is afraid of the bat.'
Getting Sublists 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, like an index, but it has two integers
separated by a colon.
● 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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
● 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,
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:] >>> spam[:]
['bat', 'rat', 'elephant'] ['cat', 'bat', 'rat', 'elephant']
● 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,
just like it can count the number of characters in a string value.
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3
● Changing Values in a List with Indexes:
Normally a variable name goes on the left side of an assignment statement, like spam =
42. However, you can also use an index of a list to change the value at that index. For
example, spam[1] = 'aardvark' means “Assign the value at index 1 in the list spam to the
string 'aardvark'.”
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'aardvark'
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2] = spam[1]
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]
● 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.
>>> [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']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']
● Removing Values from Lists :
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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']
● Working with Lists:
Let us say you want to store the names of cats, at first what you do in a easy way is:
catName1 = 'Zophie'
catName2 = 'Pooka'
catName3 = 'Simon'
catName4 = 'Lady Macbeth'
catName5 = 'Fat-tail'
catName6 = 'Miss Cleo‘
Bad way to write the program if you have many cats, so what you can do is assign
variables and list the cats
print('Enter the name of cat 1:')
catName1 = input()
print('Enter the name of cat 2:')
catName2 = input()
print('Enter the name of cat 3:')
catName3 = input()
print('Enter the name of cat 4:')
catName4 = input()
print('Enter the name of cat 5:')
catName5 = input()
print('Enter the name of cat 6:')
catName6 = input()
print('The cat names are:')
print(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' + catName4 + ' ' + catName5 + ' ' + catName6)
But,
What if you
want more than
6 cat names
Is this the
way to
write????
Again the answer
is no
● Instead of using multiple, repetitive variables, you can use a single variable
that contains a list value.
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to
stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
Output:
Enter the name of cat 1 (Or enter nothing to stop.):
Zophie
Enter the name of cat 2 (Or enter nothing to stop.):
Pooka
Enter the name of cat 3 (Or enter nothing to stop.):
Simon
Enter the name of cat 4 (Or enter nothing to stop.):
Lady Macbeth
Enter the name of cat 5 (Or enter nothing to stop.):
Fat-tail
Enter the name of cat 6 (Or enter nothing to stop.):
Miss Cleo
Enter the name of cat 7 (Or enter nothing to stop.):
The cat names are: Zophie Pooka Simon Lady Macbeth Fat-tail
Miss Cleo
● Using for Loops with Lists
A for loop repeats the code block once for each value in a list or list-like value.
for i in range(4):
print(i)
Output:
0
1
2
3
A common Python technique is to use range(len(someList)) with a for loop to iterate
over the indexes of a list.
>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
>>> for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
● 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.
>>> '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
For example, the following program lets the user type in a pet name and then checks
to see whether the name is in a list of pets.
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
Output: Enter a pet name: Footfoot
I do not have a pet named Footfoot
● 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.
>>> cat = ['fat', 'black', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
you could type this line of code:
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition = cat
The number of variables and the length of the list must be exactly equal, or Python will give
you a ValueError:
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition, name = cat
● Augmented Assignment Operators :
When assigning a value to a variable, you will frequently use the variable itself. For
example, after assigning 42 to the variable spam, you would increase the value in
spam by 1 with the following code: >>> spam = 42
>>> spam = spam + 1
>>> spam 43
As a shortcut, you can use the augmented assignment operator += to do the same
thing:
>>> spam = 42
>>> spam += 1
>>> spam
43
● There are augmented assignment operators for the +, -, *, /, and % operators:
The += operator can also do string and list concatenation, and the *= operator can do string and list replication.
>>> spam = 'Hello‘
>>> spam += ' world!‘
>>> spam
'Hello world!
1.
EXCERSISE
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 bacon.index('cat') evaluate to?
7. What does bacon.append(99) make the list value in bacon look like?
8. What does bacon.remove('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?
EXCERSISE
THANK YOU

More Related Content

Similar to IPP-M2-C1-Lists-Data Types.pptx for project management (20)

PPTX
Python Lecture 8
Inzamam Baig
 
PPTX
Pythonlearn-08-Lists.pptx
MihirDatir
 
PPTX
Pythonlearn-08-Lists.pptx
MihirDatir1
 
PDF
"Automata Basics and Python Applications"
ayeshasiraj34
 
PPTX
Module-2.pptx
GaganRaj28
 
PDF
Python elements list you can study .pdf
AUNGHTET61
 
PDF
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
horiamommand
 
PPTX
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
PPTX
Python for the data science most in cse.pptx
Rajasekhar364622
 
PPTX
updated_list.pptx
Koteswari Kasireddy
 
PPTX
An Introduction To Python - Lists, Part 2
Blue Elephant Consulting
 
PPTX
List in Python
Sharath Ankrajegowda
 
PPTX
File handling in pythan.pptx
NawalKishore38
 
PDF
Session -5for students.pdf
priyanshusoni53
 
PPTX
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
DeepakRattan3
 
DOCX
List Data Structure.docx
manohar25689
 
PPTX
Module-3.pptx
Manohar Nelli
 
PPTX
Unit 4.pptx python list tuples dictionary
shakthi10
 
Python Lecture 8
Inzamam Baig
 
Pythonlearn-08-Lists.pptx
MihirDatir
 
Pythonlearn-08-Lists.pptx
MihirDatir1
 
"Automata Basics and Python Applications"
ayeshasiraj34
 
Module-2.pptx
GaganRaj28
 
Python elements list you can study .pdf
AUNGHTET61
 
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
horiamommand
 
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
Python for the data science most in cse.pptx
Rajasekhar364622
 
updated_list.pptx
Koteswari Kasireddy
 
An Introduction To Python - Lists, Part 2
Blue Elephant Consulting
 
List in Python
Sharath Ankrajegowda
 
File handling in pythan.pptx
NawalKishore38
 
Session -5for students.pdf
priyanshusoni53
 
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
DeepakRattan3
 
List Data Structure.docx
manohar25689
 
Module-3.pptx
Manohar Nelli
 
Unit 4.pptx python list tuples dictionary
shakthi10
 

Recently uploaded (20)

PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPTX
How to Manage Promotions in Odoo 18 Sales
Celine George
 
PPTX
Explorando Recursos do Summer '25: Dicas Essenciais - 02
Mauricio Alexandre Silva
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PDF
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
PPTX
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
PDF
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
ROLE OF ANTIOXIDANT IN EYE HEALTH MANAGEMENT.pptx
Subham Panja
 
PPT
digestive system for Pharm d I year HAP
rekhapositivity
 
PPTX
Latest Features in Odoo 18 - Odoo slides
Celine George
 
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
How to Manage Promotions in Odoo 18 Sales
Celine George
 
Explorando Recursos do Summer '25: Dicas Essenciais - 02
Mauricio Alexandre Silva
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
ROLE OF ANTIOXIDANT IN EYE HEALTH MANAGEMENT.pptx
Subham Panja
 
digestive system for Pharm d I year HAP
rekhapositivity
 
Latest Features in Odoo 18 - Odoo slides
Celine George
 
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
Ad

IPP-M2-C1-Lists-Data Types.pptx for project management

  • 1. Lists, Dictionaries and structuring Data, Manipulating strings MODULE- 2
  • 2. Topics Include 1. Lists 2. Dictionaries and Structuring Data 3. Manipulating Strings a. The List Data Type, a. The Dictionary Data type, a. Working with Strings, b. Working with Lists, b. Pretty Printing, b. Useful String Methods, c. Augmented Assignment Operators, c. Using Data Structures to Model Real-World Things c. Project: Password Locker, d. Methods, d. Project: Adding Bullets to Wiki Markup e. Example Program: Magic 8 Ball with a List, f. List-like Types: Strings and Tuples.
  • 3. Objectives ● Explanation of what a list is. ● Create and index lists of simple values. ● Change the values of individual elements. ● Append values to an existing list. ● Reorder and slice list elements. ● List Concatenation and Replication. ● Multiple assignment Trick operator. ● Augmented assignment operators.
  • 5. Chapter 4: Lists ● The list data type: ✔ A list is a value that contains multiple values in an ordered sequence. Eg: ['cat', 'bat', 'rat', 'elephant']. ✔ Just as string values are typed with quote characters to mark where the string begins and ends, 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
  • 6. Hands-on with lists: 1. Typing on the console and observing the outputs: >>> [1,2,3] [1,2,3] >>> ['cat', 'bat', 'rat', 'elephant'] ['cat', 'bat', 'rat', 'elephant'] >>> ['hello', 3.1415, True, None, 42] ['hello', 3.1415, True, None, 42] >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam ['cat', 'bat', 'rat', 'elephant']
  • 7. Getting Individual Values in a List with Indexes: Let us consider a list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam. >>> 'Hello ' + spam[0] 'Hello cat‘ • Errors with List: >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[10000] Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> spam[10000] IndexError: list index out of range
  • 8. Integer values are accepted in lists, floating values are not accepted >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[1] 'bat‘ >>> spam[1.0] Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> spam[1.0] TypeError: list indices must be integers, not float >>> spam[int(1.0)] 'bat'
  • 9. Lists can also contain other list values. The values in these lists of lists can be accessed using multiple indexes >>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] >>> spam[0] ['cat', 'bat'] >>> spam[0][1] 'bat‘ >>> spam[1][4] 50
  • 10. Negative Indexes ● 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. Enter the following into the interactive shell: >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[-1] ‘elephant’ >>> spam[-3] ‘bat’ >>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.‘ 'The elephant is afraid of the bat.'
  • 11. Getting Sublists 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, like an index, but it has two integers separated by a colon. ● 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. >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[0:4] ['cat', 'bat', 'rat', 'elephant']
  • 12. >>> spam[1:3] ['bat', 'rat'] >>> spam[0:-1] ['cat', 'bat', 'rat'] ● 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, >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[:2] ['cat', 'bat'] >>> spam[1:] >>> spam[:] ['bat', 'rat', 'elephant'] ['cat', 'bat', 'rat', 'elephant']
  • 13. ● 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, just like it can count the number of characters in a string value. >>> spam = ['cat', 'dog', 'moose'] >>> len(spam) 3 ● Changing Values in a List with Indexes: Normally a variable name goes on the left side of an assignment statement, like spam = 42. However, you can also use an index of a list to change the value at that index. For example, spam[1] = 'aardvark' means “Assign the value at index 1 in the list spam to the string 'aardvark'.”
  • 14. >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[1] = 'aardvark' >>> spam ['cat', 'aardvark', 'rat', 'elephant'] >>> spam[2] = spam[1] >>> spam ['cat', 'aardvark', 'aardvark', 'elephant'] >>> spam[-1] = 12345 >>> spam ['cat', 'aardvark', 'aardvark', 12345]
  • 15. ● 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. >>> [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'] >>> spam = [1, 2, 3] >>> spam = spam + ['A', 'B', 'C'] >>> spam [1, 2, 3, 'A', 'B', 'C']
  • 16. ● Removing Values from Lists : 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. >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> del spam[2] >>> spam ['cat', 'bat', 'elephant'] >>> del spam[2] >>> spam ['cat', 'bat']
  • 17. ● Working with Lists: Let us say you want to store the names of cats, at first what you do in a easy way is: catName1 = 'Zophie' catName2 = 'Pooka' catName3 = 'Simon' catName4 = 'Lady Macbeth' catName5 = 'Fat-tail' catName6 = 'Miss Cleo‘ Bad way to write the program if you have many cats, so what you can do is assign variables and list the cats
  • 18. print('Enter the name of cat 1:') catName1 = input() print('Enter the name of cat 2:') catName2 = input() print('Enter the name of cat 3:') catName3 = input() print('Enter the name of cat 4:') catName4 = input() print('Enter the name of cat 5:') catName5 = input() print('Enter the name of cat 6:') catName6 = input() print('The cat names are:') print(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' + catName4 + ' ' + catName5 + ' ' + catName6) But, What if you want more than 6 cat names Is this the way to write???? Again the answer is no
  • 19. ● Instead of using multiple, repetitive variables, you can use a single variable that contains a list value. catNames = [] while True: print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):') name = input() if name == '': break catNames = catNames + [name] # list concatenation print('The cat names are:') for name in catNames: print(' ' + name) Output:
  • 20. Enter the name of cat 1 (Or enter nothing to stop.): Zophie Enter the name of cat 2 (Or enter nothing to stop.): Pooka Enter the name of cat 3 (Or enter nothing to stop.): Simon Enter the name of cat 4 (Or enter nothing to stop.): Lady Macbeth Enter the name of cat 5 (Or enter nothing to stop.): Fat-tail Enter the name of cat 6 (Or enter nothing to stop.): Miss Cleo Enter the name of cat 7 (Or enter nothing to stop.): The cat names are: Zophie Pooka Simon Lady Macbeth Fat-tail Miss Cleo
  • 21. ● Using for Loops with Lists A for loop repeats the code block once for each value in a list or list-like value. for i in range(4): print(i) Output: 0 1 2 3 A common Python technique is to use range(len(someList)) with a for loop to iterate over the indexes of a list. >>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders'] >>> for i in range(len(supplies)): print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
  • 22. ● 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. >>> '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
  • 23. For example, the following program lets the user type in a pet name and then checks to see whether the name is in a list of pets. myPets = ['Zophie', 'Pooka', 'Fat-tail'] print('Enter a pet name:') name = input() if name not in myPets: print('I do not have a pet named ' + name) else: print(name + ' is my pet.') Output: Enter a pet name: Footfoot I do not have a pet named Footfoot
  • 24. ● 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. >>> cat = ['fat', 'black', 'loud'] >>> size = cat[0] >>> color = cat[1] >>> disposition = cat[2] you could type this line of code: >>> cat = ['fat', 'black', 'loud'] >>> size, color, disposition = cat The number of variables and the length of the list must be exactly equal, or Python will give you a ValueError: >>> cat = ['fat', 'black', 'loud'] >>> size, color, disposition, name = cat
  • 25. ● Augmented Assignment Operators : When assigning a value to a variable, you will frequently use the variable itself. For example, after assigning 42 to the variable spam, you would increase the value in spam by 1 with the following code: >>> spam = 42 >>> spam = spam + 1 >>> spam 43 As a shortcut, you can use the augmented assignment operator += to do the same thing: >>> spam = 42 >>> spam += 1 >>> spam 43
  • 26. ● There are augmented assignment operators for the +, -, *, /, and % operators: The += operator can also do string and list concatenation, and the *= operator can do string and list replication. >>> spam = 'Hello‘ >>> spam += ' world!‘ >>> spam 'Hello world!
  • 27. 1. EXCERSISE 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].
  • 28. 6. What does bacon.index('cat') evaluate to? 7. What does bacon.append(99) make the list value in bacon look like? 8. What does bacon.remove('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? EXCERSISE