Section 3: Python Object and Data Structure Basics Flashcards
What does “Formatted String Literals (f-strings)” look like:
name = ‘Fred’
print(f”He said his name is {name}.”)
What do Lists look like?
# Assign a list to an variable named my_list my_list = [1,2,3]
How to find the number of objects in a List?
len(my_list)
How do you slice a list?
my_list = [‘one’, ‘two’, ‘three’, 4, 5]
# Grab index 1 and everything past it my_list[1:]
# Grab everything UP TO index 3 my_list[:3]
How do you add an item to a List?
# Append list1.append('append me!')
How do you remove the last item in a list and store it in a variable?
# Assign the popped element, remember default popped index is -1 popped_item = list1.pop()
How do you reverse the items in a List?
# Use reverse to reverse order (this is permanent!) new_list.reverse()
How to sort a List (so that the sort is permanent, done in place) ?
# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending) new_list.sort()
How can you nest Lists?
Let’s make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
# Make a list of lists to form a matrix matrix = [lst_1,lst_2,lst_3]
Show
matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
What does List Comprehensions look like?
# Show matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Build a list comprehension by deconstructing a for loop within a [] first_col = [row[0] for row in matrix]
first_col
[1, 4, 7]
What does a dictionary look like”
# Make a dictionary with {} and : to signify a key and a value my_dict = {'key1':'value1','key2':'value2'}
How do call a value with a dictionary?
# Call values by their key my_dict['key2']
produces:
value2
How would you subtract from a value in a dictionary?
# Subtract 123 from the value my_dict['key1'] = my_dict['key1'] - 123
How do you add a new key/value pair to a dictionary?
# Create a new key through assignment d['animal'] = 'Dog'
# Can do this with any object d['answer'] = 42
How do you create a tuple?
# Create a tuple t = (1,2,3)
# Can also mix object types t = ('one',2)