27
loading...
This website collects cookies to deliver better user experience
set_example = {1, 1, 2, 3, 3, 3}
# {1, 2, 3}
fruit_set = {'🍎', '🍓', '🍐', '🍎', '🍎', '🍓'}
# {'🍎', '🍐', '🍓'}
# Example in Python 3.5
fruit_size = {}
>>> fruit_size['🍎'] = 12
>>> fruit_size['🍐'] = 16
>>> fruit_size['🍇'] = 20
>>> fruit_size
{'🍎': 12, '🍇': 20, '🍐': 16}
You can easily switch to different versions of Python using pyenv. Try it out!
fruit_list = ['🍎', '🍓', '🍐']
fruit_list[1]
# '🍓'
animal_tuple = ('🐶', '🐱', '🐮')
animal_tuple[2]
# '🐮'
vehicle_set = {'🚐', '🏍', '🚗'}
vehicle_set[0]
# TypeError: 'set' object is not subscriptable
a_tuple = tuple(range(1000))
a_list = list(range(1000))
a_tuple.__sizeof__() # 8024 bytes
a_list.__sizeof__() # 9088 bytes
When you need to mutate your collection.
When you need to remove or add new items to your collection of items.
If your data should or does not need to be changed.
Tuples are faster than lists. We should use Tuple instead of a List if we are defining a constant set of values and all we are ever going to do with it is iterate through it.
If we need an array of elements to be used as dictionary keys, we can use Tuples. As Lists are mutable, they can never be used as dictionary keys.
So, should I always use Set or Dictionary?
“Premature optimization is the root of all evil.”