Chapter 7 and 8 Flashcards

(75 cards)

1
Q

Which of the following are mutable? Which are immutable?

Strings
Lists
Tuples

A

Mutable: Lists [ ]

  • can have index on left hand side of = operator
  • once you change the list, the ORIGINAL list is changed (don’t need a return statement in functions)

Immutable: Tuples ( ), Strings “ “

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What types of elements can be inside a list?

A

Strings, numeric literals (or mix)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the output look like:

list1 = [1, 2, “Hi”]

print(list1)

A

[1, 2, “Hi”]

  • square brackets show up in output (list data type)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you convert range(#) into a list?

e.g. range(5)

A

Use the built-in list() function to convert range (and tuples) into lists

list(range(5))

–> creates a NEW LIST = [0,1,2,3,4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you create multiple COPIES of lists and JOIN them together?

e.g. [1,2,3,4]

to

[1,2,3,4,1,2,3,4]

A

use * operator with a list

e. g. [1,2,3,4] * 2
- also works with strings and tuples!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Indexing for lists, tuples, and strings

A

variableName[index]

  • index position within square brackets
  • Positive indexes start at 0 and increase by 1 (last element has index = length of list, tuple or string - 1)
  • Negative indexes start at - 1 (last element, right to left)

Application:
- Used frequently in FOR loops, where the target variable takes on the index position

Example:
for i in range(len(list)):
list[i] += 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the output look like:

myList = [1, 2, “Hi”]

print(myList[1])
print(myList[-1])
print(myList[5])

A

2
Hi
IndexError (invalid index!!!, not like slicing)

  • no square brackets (retrieving element, kind of like a variable)

e.g. print(2) = 2
print(“Hi”) = Hi (no quotes!)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Concatenating Lists, Tuples, and Strings

A
  • Concatenation creates a NEW object (does not actually modify the original one)
  • use + operator (JOINS two objects together)
    e. g. [1, 2, 3] + [4, 5, 6]

= [1, 2, 3, 4, 5, 6]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Is this allowed?

list1 = [1,2,3,4]
string1 = "hi"

listString = list1 + string1

A

NO

  • concatenation only works with the same data type
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What will the following code display?

numbers = list(range(1, 10, 2))
for n in numbers:
print(n)

A

INTERNAL:
numbers = [1, 3, 5, 7, 9]

OUTPUT:
1
3
5
7
9
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Empty list, empty tuple, empty string

A

[]
()
“”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Given that plist has been defined to be a list of 30 elements, add 5 to its last element

A

plist[-1] += 5

e.g. [1, 2, 3, … 30]
[1, 2, 3, … 35]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What’s the difference between slicing and indexing?

What can do you slicing on?

A

Slicing takes a RANGE of elements and produces a COPY of the SAME TYPE
> therefore, you can do slicing on lists, tuples and strings

Difference:

  • slicing operation needs colons, :
  • slicing results in a copy of the same type; indexing results in a VALUE

variableName[start:end:step]

  • up to but not including end!!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

name = [‘Chris’, ‘Megan’, ‘Sally’, ‘James’]

name[1:3]
name[:3]
name[2:]
name[:]
name[2:10]
name[-10:]
name[2:1]
name[1:2:-1]
name[2:0:-1]

(same rules apply for tuples and strings)

A

ALL DEFAULT STEP = 1

name[1:3] => position 1 and 2 => [‘Megan’, ‘Sally’]
(notice square brackets and ‘ ‘)

name[:3] => position 0, 1, 2 => [‘Chris’, ‘Megan’, ‘Sally’]
- default start is 0

name[2:] => position 2, 3 => [‘Sally’, ‘James’]
- default end is length of the list, string or tuple (so will capture all elements until the end)

name[:] => entire list => [‘Chris’, ‘Megan’, ‘Sally’, ‘James’]

name[2:10] => position 2, 3 => [‘Sally’, ‘James’]

  • 10 is beyond the last index
  • NO ERROR is raised though; will get elements all the way to the end (length of the list)

name[-10:] => [‘Chris’, ‘Megan’, ‘Sally’, ‘James’]

  • -10 is beyond starting index
  • NO ERROR is raised though; will use 0 instead
  • go all the way from left to right still

name[2:1] and name[1:2:-1]
=> []
- start index is greater than end index with step value equal to 1 => RETURN AN EMPTY LIST (tuple, or string)!!!!!!!!!!!!!!!!!!!

name[2:0:-1] => [‘Sally’, ‘Megan’]

  • step value is negative
  • now start index must be greater than end index
  • start at 2, go down by 1 down to but not including position 0
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

list1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

How do you get:
[2] [20]

A

CAN’T DO print(list1[0], list1[-1])
- will result in 2 20 (no brackets)

SLICING

print(list1[0:1], list1[-1:])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

IN and NOT IN operators

What types of object types can it be used with?

A

Can be used with:

  • lists
  • tuples
  • strings

Format: item in object
item not in object
e.g. if 4 in tuple3
if ‘Sally’ not in string1

Output: Boolean
- True or False

MUST BE AN ELEMNT (not a subelement!!!)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

list1 = [[1, 2], [3, 4]]

len(list1)
3 in list1

A

Length = 2 (contains 2 sublists)

3 in list1 => FALSE (3 is an element in the sublist)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Built-in function to ADD an item to the end of the list?

A

listName.append(item)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Built-in function to REMOVE an item from the list?

e.g. remove 4 from list1
list1 = [4,2,3,4]

remove 5 from list 1?

A

listName.remove(item)

  • removes the FIRST OCCURENCE only
  • then, shifts all other elements to the left by 1 index
  • if the item does not exist, ValueError will be raised

Example:
list1.remove(4) results in
[2,3,4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Built-in function to get the INDEX of the first occurrence of an item in a list, tuple, or string?

e.g. what is the index of 4 in list1
list1 = [4,2,3,4]

What is the index of 5 in list1?

A

listName.index(item)

  • returns the INDEX of the first occurrence of item
  • if the item does not exist, ValueError

Example:
list1.index(4) results in 0

*Works for strings and tuples

Application:
- helpful to find the index of the element you want to REPLACE

e.g. index = animalList.index(‘cow’)

animalList[index] = ‘bat’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Built-in function to INSERT an item at a particular index

e.g. insert 1 in list1 right before 2
list1 = [4,2,3,4]

What if you want to insert 5 in position 10? Position -10?

A

listName.insert(index, item)

  • index first, then item
  • all items after the new item are shifted one position toward the end of the list
  • NO Value Errors are raised (simply insert at either end or beginning)

Example:
list1.insert(1, 1) results in
[4, 1, 2, 3, 4]

list1.insert(10, 5) results in
[4,1,2,3,4,5]

list1.insert(-10, 5) results in
[5,4,1,2,3,4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Built-in function to SORT elements in a list in ascending order (smallest to largest value)

A

listName.sort()

  • works for list of strings too
    e. g. Original Order = [‘beta’, ‘alpha’, ‘gamma’, ‘delta’]

Sorted Order = [‘alpha’, ‘beta’, ‘delta’, ‘gamma’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Built-in function to REVERSE the order of the elements in a list

A

listName.reverse()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Built-in function to DELETE an item located a particular INDEX

A

del listName[index]

  • shifts elements by one position to the beginning
  • if index does not exist => IndexError
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Built-in function to get MIN and MAX value in a sequence, such as a list, tuple or string
max(listName) min(listName) - for letters, based on ASCII code #s
26
Given the lists, lst1 and lst2, create a new sorted list consisting of all the elements of lst1 that also appears in lst2. For example, if lst1 is [4, 3, 2, 6, 2] and lst2 is [1, 2, 4], then the new list would be [2, 2, 4]. Note that duplicate elements in lst1 that appear in lst2 are also duplicated in the new list. Associate the new list with the variable new_list, and don't forget to sort the new list.
new_list = [] for i in range(len(lst1)): ... if lst1[i] in lst2: ....... new_list.append(lst1[i]) new_list.sort()
27
Why should you make copies of lists?
Because if you make a change to the list, then that CHANGES the elements of the list, even without a new assignment Copy of a list ensures that there are TWO SEPARATE but identical lists - copy by appending items (e.g., list2.append(item)) - or using concatenation (e.g., [] + list1)
28
What is the output: ``` list1 = [1, 2, 3, 4] list2 = list1 ``` list1[0] = 99 print(list1) print(list2)
both lists reference the SAME list Therefore BOTH list1 and list2 are equal to [99, 2, 3, 4]
29
Using list elements in a math expression
listName[index] as any other variable
30
Totaling the values in a list e.g. numList = [1,2,3,4]
- set up an accumulator variable (total = 0) OUTSIDE of the for loop for value in numList: total += value
31
Averaging the values in a list e.g. numList = [1,2,3,4]
- first, set up an accumulator variable (total = 0) OUTSIDE of the for loop - then exit the loop and divide by length of the list
32
Passing a list as an argument to a function and returning a list from a function
def function(listName): return newList - just like any other argument If passing a list through as an argument and performing calculations on the SAME list, there is NO NEED for a return statement!! (already modified inside and outside the function) e.g. def getSquare(numList): for i in range(len(numList)): numList[i] = numList[i] ** 2 #no need to return numList
33
Design a program that will read a student's test scores as input, and calculate the average with the lowest score dropped Algorithm?
1. Loop to get student's test scores (Y = continue adding) 2. Add test scores to an empty list [] using append built-in function 3. Get the total of the test scores 4. find minimum value (min(listName)) 5. subtract the lowest value from total 6. calculate average = total / length of the list minus 1
34
How do you write a list to a file? e.g. citiesList = ['NY', 'Boston', 'Atlanta']
use .writelines() or .write(item) Step 1: Open file for writing outfile = open('name.txt', 'w') Step 2: write list into the file outfile.writelines(citiesList) Step 3: close the file outfile.close() What will show up in the file? One long line NYBostonAtlanta - add '\n' in a loop when writing each element for item in citiesList: outfile.write(str(item) + '\n')
35
How do you read a list from a file?
Use .readlines() Step 1: Open file for reading infile = open('name.txt., 'r') Step 2: Grab list from the file, store into a variable citiesList = infile.readlines() Step 3: Close the file infile.close()
36
What are two dimensional lists?
Lists inside lists! Helpful to visualize as having rows and columns e.g. [[1,2,3][1,2,3]] - "Rows" = elements (2 rows) - "Column" = sub elements (3 columns)
37
Consider the following list: students = [['Joe', 'Kim'], ['Sam', 'Sue'], ['Kelly', 'Chris']] How do you access 'Sam'?
students[1][0] - need two enclosed square brackets with indexes (first one is row, second one is column)
38
How do you fill in the following list with random numbers between 1 and 100, inclusive?? values = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
OUTER LOOP = rows INNER LOOP = columns for row in range(len(values)): ...for col in range(4): ...... values[row][col] = random.randint(1,100)
39
What operations do tuples support? 10
- Indexing - Slicing - max() - min() - index() - len() - in operator - not in operator - + operator (concatenation) - * operator
40
What operations do tuples NOT support?
- reverse - sort - del - remove - append - insert
41
How do you create a tuple with just one element? | not an empty tuple
Need to add a trailing comma e. g. (1,) - if you leave out the comma, you have created an integer
42
Why do tuples exist when we can use lists?
- FASTER processing than lists (won't modify any o the data) | - tuples are also SAFE (won't change elements accidentally)
43
How do you convert a list into a tuple?
use built-in function: tuple(listName)
44
Given a variable t that is associated with a tuple whose elements are numbers, write some statements that use a while loop to count the number of times the first element of the tuple appears in the rest of the tuple, and associate that number with the variable repeats. Thus if the tuple contains (1,6,5,7,1,3,4,1), then repeats would be assigned the value 2 because after the first "1" there are two more "1"s.
- loop starts at second element (index 1) ``` repeats = 0 num = 1 ``` while num < len(t): ... if t[0] == t[num]: ...... repeats += 1 ... num += 1
45
Write a function that takes two lists (with the same number of elements) as parameters and returns a new list with the values interweaved.  For instance, if list1=["the", "brown", "jumped", "the"] and list2 = ["quick", "fox", "over", "fence"], the function would return a new list containing ["the", "quick", "brown", "fox", "jumped", "over", "the", "fence"].
(Assume you have got both lists) def combineLists(list1, list2): ``` #Create a new list. newList = [] ``` #Interweave both lists. for index in range(len(list1)): newList.append(list1[index]) newList.append(list2[index]) return newList
46
Tic tac toe game: How do you check for row equality? How do you check for column equality?
Row Equality: for i in range(3): ...if board[i][0] == board[i][1] == board[i][2] and board[i][0] != '' Column Equality: for i in range(3): ...if board[0][i] == board[1][i] == board[2][i] and board[0][i] != '' Diagonal Equality: board[0][0] == board[1][1] == board[2][2] or board[2][0] == board[1][1] == board[0][2]
47
Strings are iterable objects! Count the number of T or t in a string (user enters a sentence)
counter = 0 #set outside the for loop for ch in string: ...if ch == 't' or ch == 'T': ......counter += 1
48
What is the length of this string: 'Roses are red'
13 - spaces are considered characters and therefore have an index position!
49
If strings are immutable, why does the following code seem to modify the variable, name? ``` name = 'Carmen' name = name + ' Brown' ```
The original string in name is Carmen We then assigned name to a new string, Carmen Brown The original 'Carmen' is now unassigned Similarly, modification methods like rstrip(), upper() do not modify the original string; they return a COPY of the string
50
What is the positive index referred to by the following negative index: -5 Assume length of the sequence (list, string, tuple) is 16
Positive Index = Negative Index + Length of Sequence = -5 + 16 = 11
51
What will the following code display? myString = 'abcdefg' print(myString[2:5])
- start at position 2 - end up to but not including position 5 - step value is 1 Index positions 2, 3, 4 cde
52
Write an expression whose value is the string consisting of all the characters (starting with the sixth character) of string s
Slicing example - Index position starts at position 5 (not 6!!) s[5:] e. g. 'Jennifer' - want slice 'fer' - position 5 onwards
53
Write an expression to test if 'seven' is in 'Four score and seven years ago'
if 'seven' in 'Four score and seven years ago': - in and not in operator works for strings and tuples and lists
54
What are string methods?
FUNCTIONS that belong to strings and perform operations on strings General Format: stringName.method(argument) Returns: TRUE or FALSE (boolean expressions) String Testing Methods Include (return True or False) - .isalnum() - .isdigit() - .isalpha() - .isupper() - .islower() - .isspace() String Modification Methods Include: - .lower() - .lstrip() - .lstrip(char) - .rstrip() - .rstrip(char) - .strip() - .strip(char) - .upper() Search and replace Methods Include: - .endswith(substring) - .find(substring) - .replace(old, new) - .startswith(substring)
55
How do you check if a string contains letters, numbers, or both? Conditions to return True?
stringName.isalnum() Stands for alphanumeric Returns TRUE if the string contains ONLY letters, ONLY numbers, or BOTH letters and numbers e. g. ABC, 123, ABC123 - Must be AT LEAST one character in length FALSE: - ABC%
56
How do you check if a string contains only letters? Conditions to return True?
stringName.isalpha() Returns TRUE if the string contains only alphabetical letters e. g. ABC, abc - Must be AT LEAST one character in length FALSE: - ABC123
57
How do you check if a string contains only numbers? Conditions to return True?
stringName.isdigit() Returns TRUE if the string contains only numeric digits (integers) e. g. 123 - Must be AT LEAST one character in length FALSE: - ABC123 - 1.2 (this is because period represents punctuation)
58
How do you check if a string contains only WHITESPACE characters (\n, \t, and spaces)? Conditions to return True?
stringName.isspace() Returns TRUE if the string contains only whitespace characters - must be AT LEAST one character in length (e.g. " ") FALSE: - ABC123 - ABC - 123 - $ - ! (punctuation)
59
How do you check if a string contains characters where ALL the letters are lower case? All uppercase? Conditions to return True?
stringName.islower() stringName.isupper() Returns TRUE if the string contains all lowercase (or all uppercase) letters (can also include other characters!!) - must contain at LEAST ONE alphabetic letter (if not, will return false) e.g. islower() --> abc123 isupper() --> ABC123 FALSE: - AbC123
60
What will the following functions return: userString = '123ABC' ``` userString.isalnum() userString.isalpha() userString.isdigit() userString.isspace() userString.islower() userString.isupper() ```
userString.isalnum() => True userString.isalpha() => False userString.isdigit() => False userString.isspace() => False userString.islower() => False userString.isupper() => True
61
What will the following functions return: userString = '123abc!!' ``` userString.isalnum() userString.isalpha() userString.isdigit() userString.isspace() userString.islower() userString.isupper() ```
userString.isalnum() => False ('!!' punctuation) userString.isalpha() => False userString.isdigit() => False userString.isspace() => False userString.islower() => True userString.isupper() => False
62
How do you convert all the alphabetical numbers to lower case? Upper case? e.g. '123Abc'
stringName.lower() stringName.upper() - Any character that is NOT an alphabetical letter or already lower/uppercase remains UNCHANGED - "convert" is misleading => these methods return a COPY of the string (so you must store it to the original variable) - helpful to make case-insensitive comparisons (abc is the same as ABC is the same as Abc etc.)
63
What does lstrip() and lstrip(char) do? e. g. string1 = '\nHello!' string1. lstrip() e. g. string2 = '11Name' string2. lstrip('1')
Modification methods for strings 'l' = leading .lstrip() --> returns a COPY of the string with all leading (beginning) WHITESPACE characters (spaces, \n, \t) removed e.g. '\nHello!' becomes 'Hello!' .lstrip(char) --> returns a COPY of the string with all instances of char at the beginning of the string removed e.g. '11Name' becomes 'Name' (keeps removing left to right until reach a different character)
64
What does rstrip() and rstrip(char) do? e. g. string1 = 'Hello! ' string1. rstrip() e. g. string2 = 'Hello!!' string2. rstrip('!')
Modification methods for strings 'r' = rear .rstrip() --> returns a COPY of the string with all trailing (ending) WHITESPACE characters removed (spaces, \n, \t) e.g. 'Hello! ' becomes 'Hello!' .rstrip(char) --> returns a COPY of the string with all instances of char at the end of the string removed e.g. 'Hello!!' becomes 'Hello' (keeps removing right to left until reach a different character)
65
What does strip() and strip(char) do? e. g. string1 = '\nHello!\n' string1. strip()
Modification methods for strings strip() --> returns a COPY of the string with all leading AND trailing whitespace characters removed e.g. '\nHello!\n' becomes 'Hello!' strip(char) --> returns a COPY of the string with all leading AND trailing instances of char removed
66
How do you check if a string ends with a certain substring (e.g. -ism)?
stringName.endswith(substring) e.g. stringName.endswith('ism') Returns TRUE if the string ends with substring
67
How do you check if a string starts with a certain substring (e.g. Mr)?
stringName.startswith(substring) e.g. stringName.startswith('Mr') Returns TRUE if the string starts with substring
68
How do you get the index in the string where a substring is located? e.g. string1 = 'Hello! Jen' What is the index of Jen? What index is returned if the substring is not found?
stringName.find(substring) Returns the LOWEST index where substring is found e.g. string1.find('Jen') returns 7 (where 'J' is located) If the substring is not found in stringName, returns -1 e.g.: if position == -1: print('The word was not found')
69
How do you replace a substring with another substring? (uses copies!!) e.g. string1 = 'Hello! Jen' Replace Jen with Jared
stringName.replace(old, new) Method returns a COPY of the string with ALL INSTANCES of old replaced by new e.g. stringName.replace('Jen', 'Jared') Creates a new string = 'Hello! Jared'
70
How do you validate a user's password (check if there is at least one uppercase, one lowercase letter, and a digit)?
#Set boolean variables to false ``` has_uppercase = False has_lowercase = False has_digit = False ``` ``` #Loop through each character to check. for ch in password: if ch.isupper(): has_uppercase = True if ch.islower(): has_lowercase = True if ch.isdigit(): has_digit = True ```
71
Write code to print nine rows in decreasing length e.g. ******** (8 *s) ******* ****** ***** **** *** ** *
for i in range(8, 0, -1): copies = '*' * i print(copies)
72
What does the .split() function do? e. g. string1 = 'Hello! Jen' string1. split() string1. split('!')
- function for strings - converts the string into a LIST of strings, split at the spaces e.g. 'Hello! Jen' becomes ['Hello!', 'Jen'] (spaces disappear and become commas) If you pass an argument (must be a STRING, enclosed in ' '), the string will be split at that argument e.g. 'Hello! Jen' becomes ['Hello', ' Jen']
73
Slice the word 'code' from the sentence quote = 'Talk is cheap. Show me the code.'
quote[-5:-1] - the '.' takes up a character!
74
Given variables first and last, each of which is associated with a string, representing a first and a last name, respectively. Write an expression whose value is a string that is a full name of the form "Last, First". So, if first were associated with "alan" and last with "turing", then your expression would be "Turing,Alan". ( Note the capitalization! Note: no spaces!) And if first and last were "Florean" and "fortescue" respectively, then your expression's value would be "Fortescue,Florean".
last[0].upper() + last[1:] + ',' + first[0].upper() + first[1:] or last.capitalize() + ',' + first.capitalize()
75
Write a program with a function that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized. The program should let the user enter a string and then pass it to the function, printing out the modified string. Sample Run Enter sentence to be capitalized:hello. my name is Joe. what is your name?↵ Hello. My name is Joe. What is your name?↵
def capitalize(sentence): """ Takes a string sentence and returns a string with sentence capitalization """ for ch in range(0, len(sentence)): if i == 0: sentence = sentence[i].upper() + sentence[1:] elif sentence[i] == '.' and i != len(sentence) - 1: sentence = sentence[:i+2] + sentence[i+2].upper() + sentence[i+3:] return sentence *no need for a new string. You can just reassign the string to sentence