Data Structures Flashcards
In a 2D array, how would you access an element within an array inside the array?
ex: a_list[10][0] accesses the first element of the eleventh array
Does the ‘in’ keyword work with nested loops?
No. You must check specific arrays. Ex: if a = [1, [2, 3], 4], then (2 in a) returns false.
How do you remove something from an array?
Using ‘del’ to delete a specific value, or the entire array. Ex: del a[0] deletes the first element of a. del a deletes the entirety of a.
Using ‘pop(array)’ to remove an element from an array and return it.
How do you sort an array? (using built in functions)
array.sort() sorts the array. This directly changes the array.
What is another term for dictionaries?
Associative arrays.
What are dictionaries used for?
Storing data in key:value pairs. They do not allow duplicate keys.
How do you change, add, or delete values from a dictionary?
Using ‘del’ removes a value (or the whole dictionary).
dict[‘key’] = ‘value’ will add a new value or change a preexisting one with the same key.
How do you access the value with a key in a dictionary?
Ex. bob = {‘age’ : 27, ‘job’: CEO}
bob[‘age’] accesses 27.
How do you determine the length of an array?
len(). Works with dictionaries as well.
Ex. a = [1, 2, 3], len(a) returns 3
How does .keys() and .values() work?
They return a list of the keys and values of a dictionary, respectively.
How does .items() work?
Returns the items of a dictionary as tuples. [(key,value),(key2,value2)…]
How does ‘in’ work with dictionaries?
It checks for keys.
How would you copy a dictionary to a new variable?
dict1 = dict
dict2 = dict1.copy() #dict2 is now its own thing, not a reference to dict1
What does popitem() do?
Removes the last insterted key-value pair of a dictionary
What does .clear() do?
Removes the elements from a dictionary.
What does .get() do?
The value of the key of a dictionary. ex: dict1.get(‘keyname’) returns value
What does .setdefault() do?
Returns the value of the specified key. If the key does not exist, makes a new key:value.
dict1.setdefault(‘keyname’, ‘value’)
What does .update() do?
Includes the key:value pairs of a dictionary in another.
ex:
dict1 = dict
dict1.update(dict2) #dict1 now contains the content of dict1 and dict2
What does sorted(dict) do?
Returns a dict but sorted alphabetically.
How do you slice a list?
ex:
list1 = [a, b, c, d, e, f, g, h, i]
list1[:3] #the first 3 items of list1
list1[3:] #d, and following
list1[2:5] #from 2 (inclusive) to 5 (non inclusive)
Are strings and lists mutable?
Lists are mutable. Their values can be directly changed.
Strings are not. Their indexes cannot be directly changed.
What does .append() do?
Adds a value to the end of a list.
What does .pop() do?
Pops the last item, or item at specified index
What does .reverse() do?
Reverses the list.