Allmycats1.Py: For Loop S in List
Allmycats1.Py: For Loop S in List
py
*******************
allMyCats2.py
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)
*******************
FOR LOOP S IN LIST
for i in range(4):
print(i)
******************
******************
******************
The in and not in Operators
'howdy' in ['hello', 'hi', 'howdy', 'heyas']
******************
Multiple Assignment
>>> cat = ['fat', 'black', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
******************
>>> spam = 42
>>> spam += 1
>>> spam
43
Methods
A method is the same thing as a function, except it is “called on” a value.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
******************
Adding Values to Lists with the append() and insert() Methods
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
******************
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
******************
Example Program: Magic 8 Ball with a List
magic8Ball2.py.
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']
print(messages[random.randint(0, len(messages) - 1)]
******************
******************
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.
******************
Tuples, like strings, are immutable. Tuples cannot have their values modified, appended, or
removed.
******************
References
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
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.
Passing References
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)