Python Lists and Dictionaries Basics
Python Lists and Dictionaries Basics
Module 2
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
.IN
Textbook 1: Chapters 4 – 6 RBT: L1, L2, L3
C
Textbook 1: Al Sweigart, “Automate the Boring Stuff with Python”, 1 st Edition, No Starch Press,
N
2015. (Available under CC-BY-NC-SA license at [Link]
SY
• The items in the list are separated with the comma (,) and enclosed with the square brackets [].
• A list is a value that contains multiple values in an ordered sequence.
VT
print(L3) #displays [ ]
print(spam) #displays ['cat', 'bat', 'rat', 'elephant']
.IN
>>> spam #['cat', 'bat', 'rat', 'elephant']
>>> spam[0] #'cat'
>>> spam[1]
>>> spam[2]
#'bat'
#'rat'
C
N
>>> spam[3] #'elephant‘
SY
>>> 'The ' + spam[0] + ' ate ' + spam[2] #'The cat ate rat'
• Lists can also contain other list values. The values in these lists of lists can be accessed using
multiple indexes.
• The first index dictates which list value to use, and the second indicates the value within the list
value.
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam #[['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0][1] #'bat'
>>> spam[1][4] #50
>>> spam[2][0] #IndexError: list index out of range
>>> spam[1][5] #Index Error
Negative Indexes
• Indexes start at 0 and go up, we can also use negative integers 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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1] #'elephant'
>>> spam[-3] #'bat'
>>> spam[3] #elephant
• Indexes start at 0 and go up, we can also use negative integers 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.
.IN
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1] #'elephant'
>>> spam[-3] #'bat'
C
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.‘
N
#'The elephant is afraid of the bat.'
SY
new list.
•
VT
A slice is typed between square brackets like an index but it has 2 integers separated by a colon.
• The 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).
o In a slice, the first integer is the index where the slice starts (including) and second integer is
the index where the slice ends (Excluding) and evaluates to a new list value
We 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 and Leaving out the second index is same as
using the length of the list.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2] #['cat', 'bat'] prints elements of pos 0 and 1
>>> spam[1:] #['bat', 'rat', 'elephant'] prints all excluding 0
>>> spam[:] #['cat', 'bat', 'rat', 'elephant'] prints all
.IN
can count the number of characters in a string value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> len(spam)
C
N
Changing Values in a List with Indexes
When the bracket operator appears on the left side of an assignment, it identifies the element of
SY
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']
.IN
insert: [Link](1,23) #insert 23 in pos 1
[Link](-1,20) #insert 20 into lastpos-1
If index is not available to insert, item will be inserted at last pos
C
N
Removing Values from Lists with del Statements
The del statement can also be used on a simple variable to delete it, as if it were an “unassignment”
SY
statement.
If you try to use the variable after deleting it, you will get a NameError error because the variable no
longer exists.
U
Output:
Enter name of cat1or q to stop: candy
The cat names are: candy
Enter name of cat2or q to stop: arjun
The cat names are: candy arjun
Enter name of cat3or q to stop: q
.IN
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)
C # accepts 0 to 4
#outputs 01234
N
is same as
SY
for i in range(len(supplies)): # 0 to 3
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
.IN
if name not in myFruits:
print('I do not have a Fruit named ' + name + ' in my List')
else:
print(name + ' is in my Fruit List.')
C
N
SY
Normal Way
VT
The number of variables and the length of the list must be exactly equal, or Python will give you
a ValueError:
>>> size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
size, color, disposition, name = cat
ValueError: not enough values to unpack (expected 4, got 3)
.IN
>>> spam = spam + 1
>>> spam #43
C
As a shortcut, you can use the augmented assignment operator += to do the same thing:
>>> spam = 42
N
>>> spam += 1 #spam = spam + 1
SY
The += operator can also do string and list concatenation, and the *= operator can do string and
list replication.
>>> fruits='Apple'
>>> fruits+=' Banana'
>>> fruits+=' Mango'
>>> fruits #'Apple Banana Mango‘
>>> fruits=['Apple']
>>> fruits *=3 #fruits*3
>>> fruits #['Apple', 'Apple', 'Apple']
2.4. Methods
Methods: Finding a Value in a List with the index() Method
A method is the same thing as a function, except it is “called on” a value.
Each data type has its own set of methods.
List values have an index() method that can be passed a value, and 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
.IN
error.
>>> spam = ['hello', 'hi', 'how', 'are','you']
>>> [Link]('hello') #0
>>> [Link]('how')
>>> [Link]('hello hi')
C #2
#'hello hi' is not in list
N
When there are duplicates of the value in the list, the index of its first appearance is returned.
SY
To add new values to a list, use the append() and insert() methods.
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.
>>> fruits=['Apple','Mango','Orange']
>>> fruits # ['Apple', 'Mango', 'Orange']
>>> [Link]('Grapes')
>>> fruits #['Apple', 'Mango', 'Orange', 'Grapes']
>>> fruits=['Apple','Mango','Orange']
>>> fruits # ['Apple', 'Mango', 'Orange']
>>> [Link](1,'Grapes')
>>> fruits #['Apple', 'Grapes', 'Mango', 'Orange']
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.
.IN
>>> [Link]('Mango') #AttributeError: ‘int' object has no
attribute 'append'
The remove() method is passed the value to be removed from the list it is called on.
VT
Attempting to delete a value that does not exist in the list will result in a ValueError error.
>>> fruits=['Apple', 'Grapes', 'Mango', 'Orange']
>>> [Link]('Pineapple') #ValueError: [Link](x): x not in list
If the value appears multiple times in the list, only the first instance of the value will be removed.
>>> fruits=['Apple', 'Grapes','Apple', 'Grapes', 'Mango', 'Orange']
>>> fruits #['Apple', 'Grapes', 'Apple', 'Grapes', 'Mango', 'Orange']
>>> [Link]('Grapes')
.IN
>>> [Link]()
>>> spam #['ants', 'badgers', 'cats', 'dogs', 'elephants']
C
To sort the values in reverse order, pass True for the reverse keyword argument to have sort()
function
N
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
SY
>>> [Link](reverse=True)
>>> spam #['elephants', 'dogs', 'cats', 'badgers', 'ants']
U
sort() function cannot sort lists that have both number values and string values in them, since
VT
If you need to sort the values in regular alphabetical order, pass str. lower for the key keyword
argument in the sort() method call.
>>> spam = ['a', 'z', 'A', 'Z']
>>> [Link](key=[Link])
>>> spam #['a', 'A', 'z', 'Z']
.IN
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely', C
N
'Reply hazy try again',
SY
'Very doubtful']
print(messages[[Link](0, len(messages) - 1)]) #Output: Very doubtful
When you run this program, you’ll see that it works the same as the previous [Link]
program.
Notice the expression you use as the index into messages: [Link](0, len(messages) - 1).
This produces a random number to use for the index, regardless of the size of messages. That is,
you’ll get a random number between 0 and the value of len(messages) - 1.
The benefit of this approach is that you can easily add and remove strings to the messages list
without changing other lines of code.
If you later update your code, there will be fewer lines you have to change and fewer chances for
you to introduce bugs.
.IN
Output
Very doubtful
Concentrate and ask again C
N
My reply is no
SY
Example
>>> name='Apple‘
>>> name[0] #'A'
U
.IN
>>> new_name #'Apple is a fruit'
List is Mutable
>>> eggs=[1,2,3]
C
N
>>> eggs #[1, 2, 3]
SY
>>> eggs=[4,5,6]
>>> eggs #[4, 5, 6]
The list value in eggs isn’t being changed here; rather, an entirely new and different list value ([4,
U
.IN
TypeError: 'tuple' object does not support item assignment
If you have only one value in your tuple, you can indicate this by placing a trailing comma after the
C
value inside the parentheses. Otherwise, Python will treat as normal data type values.
N
>>> eggs1=(2)
SY
>>> eggs1 #2
>>> type(eggs1) #<class 'int'>
>>> type(('hello')) #<class 'str'>
U
VT
>>> eggs2=(2,)
>>> eggs2 #(2,)
>>> type(eggs2) #<class 'tuple'>
>>> type(('hello',)) #<class 'tuple'>
>>> list3=list('hello')
>>> list3 #['h', 'e', 'l', 'l', 'o']
2.7. References
Variables store strings and integer values
>>> spam=42
>>> cheese=spam
>>> spam=100
>>> spam #100
>>> cheese #42
When you assign a list to a variable, you are actually assigning a list reference to the variable. A
.IN
reference is a value that points to some bit of data, and a list reference is a value that points to a
list.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
C
N
>>> cheese[1] = 'Hello!'
SY
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.
def eggs(Param):
[Link]('Hello')
spam = [1, 2, 3]
eggs(spam)
.IN
>>> spam #['A', 'B', 'C', 'D']
>>> cheese #['A', 'B', 'C', 'D']
>>> cheese[0]='Z'
>>> cheese
C #['Z', 'B', 'C', 'D']
N
>>> spam #['A', 'B', 'C', 'D']
SY
>>> spam[3]='X‘
>>> spam #['A', 'B', 'C', 'X']
>>> cheese #['Z', 'B', 'C', 'D']
U
VT
If the function modifies the list or dictionary that is passed, these changes will affect the original
list or dictionary value.
For this, Python provides a module named copy that provides both the copy() and deepcopy()
functions.
[Link](), can be used to make a duplicate copy of a mutable value like a list or dictionary, not
just a copy of a reference.
Deep copy is a process in which the copying process occurs recursively. In case of deep copy, a
copy of object is copied in other object.
Any changes made to a copy of object do not reflect in the original object. In python, this is
implemented using “deepcopy()” function.
.IN
A dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written
with curly brackets { }, and they have keys and values. Indexes for dictionaries are called keys,
C
and a key with its associated value is called a key-value pair.
The main difference is that List uses index to access the elements. Dictionary uses keys to access
N
the elements. The function “ dict “ creates a new dictionary with no items. dict is the name of a
SY
Dictionaries can still use integer values as keys, just like lists use integers for indexes, but they
VT
print(d)
or
LIST DICTIONARY
List is a collection of index values pairs as that Dictionary is a hashed structure of key and
of array in c++. value pairs.
.IN
The indices of list are integers starting from 0. The keys of dictionary can be of any data type.
The elements are accessed via indices. The elements are accessed via key-values.
Items in dictionaries are unordered. First element in the list would be at index 0. But, no first
item in dictionary. Dictionaries are not ordered, they can’t be sliced like lists.
U
birthdays = {'Raju': 'Apr 19', 'Manu': 'Jul 12', 'Anup': 'Jul 9'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
.IN
The keys(), values(), and items() Methods
C
There are three dictionary methods that will return dictionary’s keys, values, or both keys and
values: keys(), values(), and items().
N
The values returned by these methods are not true lists: They cannot be modified and do not have
SY
an append() method.
But these data types (dict_keys, dict_values, and dict_items, respectively) can be used in for loops.
A for loop iterates over each of the values in the spam dictionary
U
Example
VT
A for loop can also iterate over the keys or both keys and values:
spam = {'color': 'red', 'age': 42}
for k in [Link]():
print(spam[k]) # red 42
for i in [Link]():
print(i) #('color', 'red') ('age', 42)
Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or
key-value pairs in a dictionary. The values in the dict_items value returned by the items() method
are tuples of the key and value.
spam = {'color': 'red', 'age': 42}
for k in [Link]():
print(spam[k]) # red 42
for i in [Link]():
print(i) #('color', 'red') ('age', 42)
The get() method returns the value of the item with the specified key.
Syntax: [Link](keyname, value)
Parameter Values
.IN
Keyname Required The keyname of the item you want to return the value from
value Optional A value to return if the specified key does not exist. Default value
None
C
N
The get() Method
SY
Items in the dictionary can be accessed by referring to its key name, inside square brackets. Get
the value of the "model" key:
>>> d = { "brand": "toyota", "model": "etios liva", "year": 2011 }
U
Output: 'I bought toyota car etios liva model in the year 2011‘
If no key in the dictionary, the default value 0 is returned by the get() method. If no get method is
used and no key present in dictionary, then ERROR will be raised.
>>> car={'brand': 'toyota', 'model': 'etios liva', 'year': 2011}
>>> I bought '+str(car['brand']) + ' color: ' + str(car['color'])
Output: KeyError: 'color'
.IN
The setdefault() Method
C
To set a value in a dictionary for a certain key only if that key does not already have a value, then
setdefault() method is used.
N
SY
General Way
fruits = {'name': 'Apple', 'cost': 90}
if 'color' not in fruits:
U
fruits['color'] = 'green'
VT
print(fruits)
Using setdeault
fruits = {'name': 'Apple', 'cost': 90}
[Link]('color', 'black')
print(fruits)
Using setdeault
fruits = {'name': 'Apple', 'cost': 90,'color': 'Red'}
print(fruits)
[Link]('color', 'green')
print(fruits)
The setdefault() method is a nice shortcut to ensure that a key exists. Here is a short program that
counts the number of occurrences of each letter in a string.
Example
message = 'Application Development using Python Programming'
count = {}
for character in message:
.IN
[Link](character, 0)
count[character] = count[character] + 1
print(count)
C
#{'A': 1, 'p': 3, 'l': 2, 'i': 4, 'c': 1, 'a': 2, 't': 3, 'o': 4, 'n': 5, ' ': 4, 'D': 1, 'e': 3, 'v': 1, 'm': 3, 'u': 1, 's': 1,
N
'g': 3, 'P': 2, 'y': 1, 'h': 1, 'r': 2}
SY
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
U
a default value of 0) so the program doesn’t throw a KeyError error when count[character] =
VT
count[character] + 1 is executed.
count[character] = count[character] + 1
[Link](count)
The [Link]() function is especially helpful when the dictionary itself contains nested lists or
dictionaries.
.IN
2.10. Using Data Structures to Model Real-World Things
In algebraic chess notation, the spaces on the chessboard are identified by a number and letter coordinate
C
N
SY
U
VT
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, you can assign each slot a string-value key. String values
'X', 'O', or ' ' (a space character) are used in each slot on the board which needs to store nine strings.
So, dictionary can be used. 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.
.IN
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': '
', 'low-M': ' ', 'low-R': ' '}
C
N
SY
U
VT
theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M': 'X', 'mid-R': ' ','low-
L': ' ', 'low-M': ' ', 'low-R': 'X'}
Player O wins
.IN
theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O',
'mid-L': 'X', 'mid-M':'X', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': 'X'}
def printBoard(board): C
N
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
SY
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
U
printBoard(theBoard)
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-
M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
.IN
turn = 'X'
printBoard(theBoard)
C
N
Nested Dictionaries and Lists
In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries
SY
.IN
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
C
N
SY
for x in d:
print(x) # brand model year
You can also use the values() function to return values of a dictionary:
for x in [Link]():
print(x) # Toyota etios liva 2018
.IN
if "model" in d:
print("Yes, 'model' is one of the keys in the dictionary d")
C
To determine how many items (key-value pairs) a dictionary has, use the len() method.
Example: Print the number of items in the dictionary:
N
d = { "brand": "toyota", "model": "etios liva", "year": 2011 }
SY
print(len(d))
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
U
print(d)
#{'brand': 'Toyota', 'model': 'Etios liva', 'year': 2011, 'color': 'White'}
.IN
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
del d
print(d) #this will cause an error because "d" no longer exists.
C
N
Removing Items: clear()
The clear() method empties the dictionary:
SY
Copy a Dictionary
Cannot copy a dictionary using dict2 = dict1, because: dict2 will only be a reference to dict1, and
changes made in dict1 will automatically reflects in dict2.
To make a copy, use the built-in Dictionary method copy().
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
myd = [Link]()
print(myd)
# {'brand': 'Toyota', 'model': 'Etios liva', 'year': 2011}
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)
# {'W': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 1, 'm': 1}
Dictionaries have a method called “get” that takes a key and a default value. If the key appears in
the dictionary, get returns the corresponding value; otherwise it returns the default value.
For example:
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
.IN
print([Link]('year', 0)) #or print([Link]('year')) #2011
print([Link]('color', 0)) #0
print([Link]('color', 'white'))
C
#white
N
The get method automatically handles the case where a key is not in a dictionary, we can reduce
four lines down to one and eliminate the if statement.
SY
word = 'welcome'
d = dict()
for c in word:
U
d[c] = [Link](c,0) + 1
VT
Example: if we wanted to find all the entries in a dictionary with a value above ten, we could
write the following code:
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
for key in counts:
if counts[key] > 10 :
print(key, counts[key]) # annie 42 jan 100
.IN
lst = list([Link]())
print(lst) #['chuck', 'annie', 'jan']
[Link]()
for key in lst:
C
N
print(key, counts[key]) # annie 42 chuck 1 jan 100
SY
.IN
C
N
Working with Strings - Raw Strings
SY
You can place an r before the beginning quotation mark of a string to make it a raw string. A raw
string completely ignores all escape characters and prints any backslash that appears in the string.
Because this is a raw string, Python considers the backslash as part of the string and not as the start
U
of an escape Character.
VT
Raw strings are helpful if you are typing string values that contain many backslashes
>>> print(r'That is Carol\'s cat.')
Output: That is Carol\'s cat.
Single quote character in any word (ex: Eve's) does not need to be escaped. Escaping single and
double quotes is optional in raw strings. The following print() call would print identical text but
doesn’t use a multiline string:
print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and
extortion.\n\nSincerely,\nBob')
Hash character (#) marks the beginning of a comment till the end of line. A multiline string is
often used for comments that span multiple lines.
""" This is a test Python program.
Written by Al Sweigart al@[Link]
.IN
This program was designed for Python 3, not Python 2.
"""
def spam():
C
N
"""This is a multiline comment to help
SY
‘ H e l l o w o r l d ! ‘
0 1 2 3 4 5 6 7 8 9 10 11
Slicing a string does not modify the original string. You can capture a slice from one variable in
to a separate variable.
>>> spam = 'Hello world!‘
.IN
>>> fizz=spam[0:4]
>>> fizz #'Hell'
>>> spam
C #'Hello world!'
N
The in and not in Operators with Strings
SY
The in and not in operators can be used with strings just like with list values. An expression with
two strings joined using in or not in will evaluate to a Boolean True or False.
>>> 'Hello' in 'Hello World‘ #True
U
#False
>>> '' in 'spam‘ #True
>>> 'cats' not in 'cats and dogs‘ #False
>>> ' ' in 'spam‘ #False
The upper() and lower() methods are helpful if you need to make a case-insensitive comparison.
print('How are you?')
feeling = input()
if [Link]() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')
.IN
The strings 'great' and 'GREat' are not equal to each other. But, it does not matter whether the user
C
types Great, GREAT, or grEAT, because the string is first converted to lowercase.
The isupper() and islower() methods will return a Boolean True value if the string has at least one
N
letter and all the letters are uppercase or lowercase, respectively. Otherwise, the method returns
SY
False.
>>> spam = 'Hello world!'
>>> [Link]() #False
U
.IN
isspace() returns True if the string consists only of spaces, tabs, and new-lines and is not blank.
istitle() returns True if the string consists only of words that begin with an uppercase letter
followed by only lowercase letters.
>>> 'hello'.isalpha()
>>> 'hello123'.isalpha()
C #True
#False
N
>>> 'hello123'.isalnum() #True
SY
Example
while True:
print('Enter your age:')
age = input()
if [Link]():
break
print('Please enter a number for your age.')
while True:
The startswith() and endswith() methods return True if the string value they are called on begins
or ends (respectively) with the string passed to the method; Otherwise, they return False.
>>> 'Hello world!'.startswith('Hello') #True
>>> 'Hello world!'.endswith('world!') #True
>>> 'abc123'.startswith('abcdef') #False
.IN
>>> 'abc123'.endswith('12') #False
>>> 'Hello world!'.startswith('Hello world!') #True
>>> 'Hello world!'.endswith('Hello world!') #True
C
N
The join() and split() String Methods
The join() method is useful when you have a list of strings that need to be joined together into a
SY
The returned string is the concatenation of each string in the passed-in list. join() is called on a
string value and is passed a list value.
VT
A common use of split() is to split a multiline string along the newline characters.
>>> spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob''‘
>>> [Link]('\n')
.IN
The rjust() and ljust() string methods return a padded version of the string they are called on,
with spaces inserted to justify the text. The first argument to both methods is an integer length
for the justified string.
>>> 'Hello'.rjust(10)
C#' Hello'
N
>>> 'Hello'.rjust(20) #' Hello'
SY
An optional second argument to rjust() and ljust() will specify a fill character other than a space
VT
character.
>>> 'Hello'.rjust(20, '*') #'***************Hello'
>>> 'Hello'.ljust(20, '-') #'Hello --------------‘
The center() string method works like ljust() and rjust() but centers the text rather than justifying
it to the left or right.
>>> 'Hello'.center(20) #' Hello '
>>> 'Hello'.center(20, '=') #'=======Hello========'
Example
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in [Link]():
Example
---PICNIC ITEMS--
sandwiches.. 4
apples ....... 12
cups .......... 4
cookies..... 8000
.IN
-------PICNIC ITEMS-------
sandwiches .............. 4
apples ................ 12
cups ................... 4
C
N
cookies.............. 8000
SY
beginning or end.
VT
The lstrip() and rstrip() methods will remove whitespace characters from the left and right ends,
respectively.
>>> spam = ' Hello World '
>>> [Link]() #'Hello World'
>>> [Link]() #’ Hello World'
>>> [Link]() #'Hello World '
A string argument will specify which characters on the ends should be stripped.
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> [Link]('ampS') #'BaconSpamEggs‘
>>> [Link]('Spam') #'BaconSpamEggs‘
>>> [Link]('pSma') #'BaconSpamEggs'
Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital S from the
ends of the string stored in spam.
The order of the characters in the string passed to strip() does not matter: strip('ampS') will do the
same thing as strip('mapS') or strip('Spam').
The pyperclip module has copy() and paste() functions that can send text to and receive text from
your computer’s clipboard.
Sending the output of your program to the clipboard will make it easy to paste it to an email, word
processor, or some other software.
Pyperclip does not come with [Link] install it, run command prompt in administrator mode.
Go to the directory where python is installed and run the following command
pip install pyperclip
.IN
Then, pyperclip module can be used.
>>> import pyperclip
C
>>> [Link]('Hello world!')
>>> [Link]()
N
or
SY
import pyperclip as pc
[Link]('Hello world!')
[Link]()
U
VT
.IN
[Link]()
account = [Link][1] # first command line arg is the account name
Step 3: Copy the Right Password
if account in PASSWORDS:
C
N
[Link](PASSWORDS[account])
SY
Run the file in command prompt and pass email as value in command prompt
VT
m2_project-[Link] email
Password for email copied to clipboard
b. Do something to it
c. Copy the new text to the clipboard
Step 2: Separate the Lines of Text and Add the Star
Step 3: Join the Modified Lines
.IN
# TODO: Separate lines and add stars.
[Link](text)
Step 2: Join the Modified Lines
C
The call to [Link]() returns all the text on the clipboard as one big string. If we used the
N
“List of Lists of Lists”
SY
import pyperclip
VT
text = [Link]()
# Separate lines and add stars.
lines = [Link]('\n')
for i in range(len(lines)): # loop through all indexes in the "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
[Link](text)
Step 3: Join the Modified Lines
import pyperclip
text = [Link]()
# Separate lines and add stars.
lines = [Link]('\n')
for i in range(len(lines)): # loop through all indexes for "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
[Link](text)
import pyperclip
text = [Link]() #text copied from project 1(prev prg) output
print(text)
# TODO: Separate lines and add stars.
[Link](text)
text = [Link]()
# Separate lines and add stars.
lines = [Link]('\n')
for i in range(len(lines)): # loop through all indexes in the "lines" list
.IN
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
[Link](text)
print(lines)
C
N
SY
U
VT
List element modification involves changing the value at a specific index using direct assignment like list[index] = new_value. Append() and insert() add new elements, while del and pop() remove them . In contrast, dictionary key-value pairs are modified by directly assigning a new value to a key (e.g., dict[key] = new_value). Additional methods like update() can update multiple keys at once, while methods like pop() remove a key-value. The operations in dictionaries are indexed by keys instead of position indices seen in lists .
Python lists allow for dynamic modeling by enabling addition, deletion, and modification of elements flexibly. For instance, elements can be appended using the append() method or inserted at specific positions using insert(), and they can be accessed or removed by their indexes with operations like del . Dictionaries provide dynamic modeling by allowing key-value pairs to be added, modified, and deleted, supporting operations like using the pop() method to remove items, setdefault() to ensure keys exist, and the get() method for safe retrieval of values . These features of lists and dictionaries support complex data structures for real-world data representation.
The get() method allows retrieval of a key's value with an optional default value if the key does not exist, preventing KeyErrors. setdefault(), on the other hand, sets a key with a default value only if the key doesn’t already exist. These methods are useful in scenarios like data processing where missing keys are common—they ensure smooth code execution without errors from absent keys. For instance, using get() to provide default values when compiling reports from data dictionaries helps avoid interruptive errors .
Accessing a list item using an index returns a single element, while using a slice returns a new list containing the elements from the specified start index up to but not including the end index. If one or both indices are omitted, the slice defaults to start from the beginning (if the start index is omitted) or end at the list's length (if the end index is omitted). For example, spam[2] accesses a single value, while spam[1:4] creates a new list with elements from index 1 to 3 inclusive. Leaving out indices like spam[:2] returns elements from the start up to index 1, and spam[1:] returns all elements from index 1 to the end of the list .
Nested lists extend the capabilities of basic lists by representing multi-dimensional data structures like matrices or tables. They allow access to individual sub-elements using multiple indices, providing a structured approach to handle complex datasets. However, challenges arise in terms of increased complexity in data manipulation tasks; navigating nested elements requires careful index management and understanding of the nested structure’s logic. Operations like flattening a nested list or mapping functions over nested elements require advanced iterative or recursive strategies .
Negative indexing begins counting from the end of the list, whereas positive indexing starts from the beginning. A negative index of -1 refers to the last element, -2 to the second last, and so forth. This allows for easy access to end-based elements without needing to know the list’s length, which can be useful for operations involving the last few elements of a list .
Using references instead of copies for lists and dictionaries means that changes made to the data structure through any reference affect all references, as they point to the same memory location. This can lead to unintended side effects, where modifications in one part of a program inadvertently impact another. To avoid such issues, a deep copy (e.g., using the copy() method for dictionaries) should be used when independent manipulation is required, ensuring that changes to one copy do not affect another .
Strings and tuples differ from lists primarily in their immutability; changes cannot be made to individual elements after creation, unlike lists which are mutable. This makes strings and tuples more suitable for fixed sequences of data, where integrity is critical. Tuples are often used as keys in dictionaries due to their hashable nature, while strings are used for text manipulation and storage. Lists, on the other hand, allow dynamic changes, expansions, and contractions, making them ideal for tasks where a variable collection of elements is needed .
The len() function returns the number of elements in a list, aiding in iteration and boundary setting. append() adds elements to the end of the list, allowing for growth without manually managing indices. pop() removes and returns a specified item, while popitem() (primarily used with dictionaries) removes the last item. Using these methods incorrectly, such as calling pop() on an index out of range, could lead to IndexErrors, or altering list length and indices without recalculating them might produce logic errors .
Pretty-printing a dictionary involves formatting it to be more readable by aligning key-value pairs in a structured format. This can be achieved using libraries such as pprint or methods like pretty print (available in some Python implementations), which automatically format nested structures into indented, cleanly spaced lines. Pretty-printing is useful in debugging, data analysis, and logging, where clear visibility of data structures is crucial for effective comprehension and decision-making .