I am currently starting to learn python, i would like to know what would be the difference in usage of a tuple and a dictionary, also if using the JSON format would make ir more readable, please, if there is somebody that coul help me to figure out when to use one or another.
A very opinionated short overview:
- Use list for values of the same type. Lists can be modified.
- Use tuples for values of different types. Tuples are immutable, this is sometimes desired.
- Use named tuples for values of different types which shall be accessed with a name. Also immutable.
- Use dictionary for accessing values by names. Dictionaries can be modified.
- Use data classes if you have special needs. Data classes are classes with nice features for aggregating data.
1 Like
If you’re asking about tuples and dicts, I can only imagine you’re thinking about functions which return some number of variables, because in most other contexts list would be a strong contender.
My own rule of thumb is:
- If a function returns 3 or less variables, return as a tuple. (For easy automatic unpacking.)
- If a combination of variables occurs together often, whether as function output or function input, create a dataclass. (From dataclasses.dataclass)
- Otherwise, a dict is probably fine.
I largely agree with Kurt, but:
- Lists are one of the very attractive features of python. Lists are easy to create, inspect, concatenate, modify, etc. Lists are typically used for items you can imagine iterating over, which might mean they are the same type, but it might not.
- In any situation where it is worth creating a named tuple, it is worth creating a dataclass instead. Use
slots=True, frozen=True
for bonus points. Compare:
from collections import namedtuple
# Define a named tuple called 'Point'
Point = namedtuple('Point', ['x', 'y'])
# Create an instance of the named tuple
p = Point(1, 2)
print(p)
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class Point:
x: int
y: int
# Create an instance of the dataclass
p = Point(1, 2)
print(p)
In return for a few extra characters, you get protection from accidental tuple unpacking.
Although perhaps I shouldn’t recommend beginners to use slots. It causes the occasional headache.
1 Like