In short, use:
list
- if you require an ordered sequence of items.
dict
- if you require to relate values with keys
set
- if you require to keep unique elements.
A list is a mutable sequence, typically used to store collections of homogeneous items.
A list implements all of the common sequence operations:
x in l
and x not in l
l[i]
, l[i:j]
, l[i:j:k]
len(l)
, min(l)
, max(l)
l.count(x)
l.index(x[, i[, j]])
- index of the 1st occurrence of x
in l
(at or after i
and before j
indeces)A list also implements all of the mutable sequence operations:
l[i] = x
- item i
of l
is replaced by x
l[i:j] = t
- slice of l
from i
to j
is replaced by the contents of the iterable t
del l[i:j]
- same as l[i:j] = []
l[i:j:k] = t
- the elements of l[i:j:k]
are replaced by those of t
del l[i:j:k]
- removes the elements of s[i:j:k]
from the listl.append(x)
- appends x
to the end of the sequence l.clear()
- removes all items from l
(same as del l[:]
)l.copy()
- creates a shallow copy of l
(same as l[:]
)l.extend(t)
or l += t
- extends l
with the contents of t
l *= n
- updates l
with its contents repeated n
timesl.insert(i, x)
- inserts x
into l
at the index given by i
l.pop([i])
- retrieves the item at i
and also removes it from l
l.remove(x)
- remove the first item from l
where l[i]
is equal to xl.reverse()
- reverses the items of l
in placeA list could be used as stack by taking advantage of the methods append
and pop
.
A dictionary maps hashable values to arbitrary objects. A dictionary is a mutable object. The main operations on a dictionary are storing a value with some key and extracting the value given the key.
In a dictionary, you cannot use as keys values that are not hashable, that is, values containing lists, dictionaries or other mutable types.
A set is an unordered collection of distinct hashable objects. A set is commonly used to include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.