Senior
What data types are available in Python? How does list differ from tuple?
sobes.tech AI
Answer from AI
Python has several basic data types:
- Numbers:
int,float,complex - Boolean type:
bool - Sequences:
list,tuple,range - Strings:
str - Sets:
set,frozenset - Dictionaries:
dict - Others:
bytes,bytearray,NoneType
Differences between list and tuple:
listis a mutable data type, elements can be added, removed, and changed.tupleis immutable, its contents cannot be changed after creation.
Due to immutability, tuples (tuple) are usually used to store fixed sets of data and can be faster and safer to use, for example, as dictionary keys (if they contain only hashable elements). Lists are convenient for dynamic collections where modification of contents is required.
Example:
my_list = [1, 2, 3]
my_list.append(4) # works
my_tuple = (1, 2, 3)
# my_tuple.append(4) # will raise an AttributeError