Chapter 7 and 8 Flashcards
(75 cards)
Which of the following are mutable? Which are immutable?
Strings
Lists
Tuples
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 “ “
What types of elements can be inside a list?
Strings, numeric literals (or mix)
What does the output look like:
list1 = [1, 2, “Hi”]
print(list1)
[1, 2, “Hi”]
- square brackets show up in output (list data type)
How do you convert range(#) into a list?
e.g. range(5)
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 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]
use * operator with a list
e. g. [1,2,3,4] * 2
- also works with strings and tuples!
Indexing for lists, tuples, and strings
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
What does the output look like:
myList = [1, 2, “Hi”]
print(myList[1])
print(myList[-1])
print(myList[5])
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!)
Concatenating Lists, Tuples, and Strings
- 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]
Is this allowed?
list1 = [1,2,3,4] string1 = "hi"
listString = list1 + string1
NO
- concatenation only works with the same data type
What will the following code display?
numbers = list(range(1, 10, 2))
for n in numbers:
print(n)
INTERNAL:
numbers = [1, 3, 5, 7, 9]
OUTPUT: 1 3 5 7 9
Empty list, empty tuple, empty string
[]
()
“”
Given that plist has been defined to be a list of 30 elements, add 5 to its last element
plist[-1] += 5
e.g. [1, 2, 3, … 30]
[1, 2, 3, … 35]
What’s the difference between slicing and indexing?
What can do you slicing on?
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!!
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)
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
list1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
How do you get:
[2] [20]
CAN’T DO print(list1[0], list1[-1])
- will result in 2 20 (no brackets)
SLICING
print(list1[0:1], list1[-1:])
IN and NOT IN operators
What types of object types can it be used with?
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!!!)
list1 = [[1, 2], [3, 4]]
len(list1)
3 in list1
Length = 2 (contains 2 sublists)
3 in list1 => FALSE (3 is an element in the sublist)
Built-in function to ADD an item to the end of the list?
listName.append(item)
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?
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]
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?
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’
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?
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]
Built-in function to SORT elements in a list in ascending order (smallest to largest value)
listName.sort()
- works for list of strings too
e. g. Original Order = [‘beta’, ‘alpha’, ‘gamma’, ‘delta’]
Sorted Order = [‘alpha’, ‘beta’, ‘delta’, ‘gamma’]
Built-in function to REVERSE the order of the elements in a list
listName.reverse()
Built-in function to DELETE an item located a particular INDEX
del listName[index]
- shifts elements by one position to the beginning
- if index does not exist => IndexError