Data Structures Flashcards

1
Q

What are the basic built-in data structures in Python?

A

Lists, Tuples, Sequences, Sets, Dictionaries

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

list.append(x)

A

Add an item to the end of the list. Equivalent to a[len(a):] = [x].

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

list.extend(iterable)

A

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

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

list.insert(i, x)

A

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

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

list.remove(x)

A

Remove the first item from the list whose value is x. It is an error if there is no such item.

>>> a=[1,2,3,4,2,6,7,8]
>>> a
[1, 2, 3, 4, 2, 6, 7, 8]
>>> a.remove(2)
>>> a
[1, 3, 4, 2, 6, 7, 8]
>>> a.remove(9)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: list.remove(x): x not in list
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

list.pop([i])

A

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

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

list.clear()

A

Remove all items from the list. Equivalent to del a[:].

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

list.index(x[, start[, end]])

A

Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

>>> a=[1,2,3,4,2,6,7,8]
>>> a.index(2)
1
>>> a.index(2,3)
4
>>> a.index(2,8)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: 2 is not in list
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

list.count(x)

A

Return the number of times x appears in the list.

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

list.sort(key=None, reverse=False)

A
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
>>> a=[1,10,2,3,4,2,6,7,8]
>>> a.sort(key=lambda x: x%2)
>>> a
[10, 2, 4, 2, 6, 8, 1, 3, 7]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

list.reverse()

A

Reverse the elements of the list in place.

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

list.copy()

A

Return a shallow copy of the list. Equivalent to a[:].

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

list copy is shallow, explain why

A

?

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

What do insert, remove or sort return?

A

They return the default None. This is a design principle for all mutable data structures in Python.
Other languages may return the mutated object, which allows method chaining, such as d->insert(“a”)->remove(“b”)->sort();.

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

Can we use lists as stack?

A

Yes. By using append and pop methods.

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

Can we use lists as queues?

A

Yes but its slow. Making insertions and deletions to the beginning of a list is slow because all of the other elements have to be shifted by one.

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

Since using list as queue is slow, what can we use instead?

A

collections.deque which was designed to have fast appends and pops from both ends.

> > > from collections import deque
queue = deque([“Eric”, “John”, “Michael”])
queue.append(“Terry”) # Terry arrives
queue.append(“Graham”) # Graham arrives
queue.popleft() # The first to arrive now leaves
‘Eric’
queue.popleft() # The second to arrive now leaves
‘John’
queue # Remaining queue in order of arrival
deque([‘Michael’, ‘Terry’, ‘Graham’])

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

Give examples to create a squares list

A
1-
>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> x
9

NOTE: x variable still exists after loop terminates

2-
squares = list(map(lambda x: x**2, range(10)))

3-
squares = [x**2 for x in range(10)]

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

> > > [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

A

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it’s equivalent to:

>>>
>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

> > > vec = [-4, -2, 0, 2, 4]

|&raquo_space;>[x*2 for x in vec]

A

[-8, -4, 0, 4, 8]

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

> > > vec = [-4, -2, 0, 2, 4]

|&raquo_space;> [x for x in vec if x >= 0]

A

[0, 2, 4]

22
Q

> > > vec = [-4, -2, 0, 2, 4]

|&raquo_space;> [abs(x) for x in vec]

A

[4, 2, 0, 2, 4]

23
Q

> > > vec = [[1,2,3], [4,5,6], [7,8,9]]

|&raquo_space;> [num for elem in vec for num in elem]

A

[1, 2, 3, 4, 5, 6, 7, 8, 9]

24
Q

> > > freshfruit = [’ banana’, ‘ loganberry ‘, ‘passion fruit ‘]
[weapon.strip() for weapon in freshfruit]

A

[‘banana’, ‘loganberry’, ‘passion fruit’]

25
Q

> > > [(x, x**2) for x in range(6)]

A

[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

26
Q

> > > [x, x**2 for x in range(6)]

A

the tuple must be parenthesized, otherwise an error is raised

File “”, line 1, in
[x, x**2 for x in range(6)]
^
SyntaxError: invalid syntax

27
Q

> > > from math import pi

|&raquo_space;> [str(round(pi, i)) for i in range(1, 6)]

A

[‘3.1’, ‘3.14’, ‘3.142’, ‘3.1416’, ‘3.14159’]

28
Q
>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

> > > list(zip(*matrix))
???

A

zip() makes an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples.
so the result is:
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

29
Q

What is del used for in a list?

A

It is used for deleting a specific element from the list or deleting the entire list:

>>> del a[:]
>>> a
[]
>>> del a
>>> a
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'a' is not defined
>>>
30
Q

What are the sequence data types in Python and why they are called sequence data types?

A

There are three basic sequence types: lists, tuples, and range objects. XXX answer the second

31
Q

What is a tuple?

A

It is a sequence data types which consists a number of comma separated values. Tuples are immutable. They can be nested.

32
Q

Give examples to tuples.

A
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
33
Q

t = 12345, 54321, ‘hello!’
x, y, z = t
a = t

A
>>> x
12345
>>> y
54321
>>> z
'hello!'
>>> a
(12345, 54321, 'hello!')
>>> a,b=t
Traceback (most recent call last):
  File "", line 1, in 
ValueError: too many values to unpack (expected 2)

Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

34
Q

How does data type Set works?

A

A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

35
Q

Give examples to set data type operations

A

> > > basket = {‘apple’, ‘orange’, ‘apple’, ‘pear’, ‘orange’, ‘banana’}
print(basket) # show that duplicates have been removed
{‘orange’, ‘banana’, ‘pear’, ‘apple’}
‘orange’ in basket # fast membership testing
True
‘crabgrass’ in basket
False

> > > # Demonstrate set operations on unique letters from two words…
a = set(‘abracadabra’)
b = set(‘alacazam’)
a # unique letters in a
{‘a’, ‘r’, ‘b’, ‘c’, ‘d’}
a - b # letters in a but not in b
{‘r’, ‘d’, ‘b’}
a | b # letters in either a or b
{‘a’, ‘c’, ‘r’, ‘d’, ‘b’, ‘m’, ‘z’, ‘l’}
a & b # letters in both a and b
{‘a’, ‘c’}
a ^ b # letters in a or b but not both
{‘r’, ‘d’, ‘b’, ‘m’, ‘z’, ‘l’}

36
Q

What is a lit comprehension?

A

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
Ex.
squares = list(map(lambda x: x**2, range(10)))

37
Q

What are dictionary data types?

A

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys. Duplicate keys not allowed, does not give error but overrides:
»> tel = {‘jack’: 4098, ‘sape’: 4139, ‘jack’:123}
»> tel
{‘jack’: 123, ‘sape’: 4139}

38
Q

What can be a key for dictionary?

A

which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

39
Q

What are the main operations that can be performed on lists?

A
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). [2] To check whether a single key is in the dictionary, use the in keyword.
40
Q

Give some examples to dictionary operations,

A
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
The dict() constructor builds dictionaries directly from sequences of key-value pairs:

> > > dict([(‘sape’, 4139), (‘guido’, 4127), (‘jack’, 4098)])
{‘sape’: 4139, ‘jack’: 4098, ‘guido’: 4127}
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

> > > {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

> > > dict(sape=4139, guido=4127, jack=4098)
{‘sape’: 4139, ‘jack’: 4098, ‘guido’: 4127}

41
Q

How to loop through dictionaries?

A

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

>>>
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave
42
Q

How to loop through sequences?

A

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>>
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe
43
Q

How to loop through two or more sequences?

A

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

> > > questions = [‘name’, ‘quest’, ‘favorite color’]
answers = [‘lancelot’, ‘the holy grail’, ‘blue’]
for q, a in zip(questions, answers):
… print(‘What is your {0}? It is {1}.’.format(q, a))

What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue

44
Q

How to loop through sequences in reverse order?

A

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>>
>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1
45
Q

How to loop through sequences in sorted order?

A

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

>>>
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear
46
Q

What is “in” and “not in” for?

A

To check whether a value occurs (does not occur) in a sequence. All comparison operators have the same priority, which is lower than that of all numerical operators.

47
Q

What is “is” and “is not” for?

A

To compare whether two objects are really the same object; this only matters for mutable objects like lists. All comparison operators have the same priority, which is lower than that of all numerical operators.

48
Q

Can comparisons be chained?

A

Yes. For example, a < b == c tests whether a is less than b and moreover b equals c.

49
Q

How does short-circuit operations work?

A

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

> > > string1, string2, string3 = ‘’, ‘Trondheim’, ‘Hammer Dance’
non_null = string1 or string2 or string3
non_null
‘Trondheim’

50
Q

How comparison for sequences and other data types work?

A

Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.