Tuple-list vs Array-vector in Python
- Tuple: Unlike List
List=[], tupletuple=()are Immutable (cannot be changed once created)
myTuple = (1, 2, 3);myTuple[0] = 100 β TypeError- List is slower than tuple due to mutability
- List take more memory due to its dynamic nature
- In tuple has no methods for modifying( like
.append(),.remove,.sort(), etc.) content, but have accessing methods like.count(),.index() - Both lists and tuples can store nested structures like
nested_list = [[1, 2], [3, 4]] # list of listnested_tuple = ((1, 2), (3, 4)) # tuple of tuplesmixed = ([1, 2], (3, 4)) # tuple of lists- Since tuples are immutable, they can be used as keys in dictionaries, while lists cannot be used as keys.
# Using a tuple as a dictionary keymy_tdict = {(1, 2): "tuple_key"}my_ldict = {[1, 2]: "list_key"} # β TypeErrorC++ Vs Python
Section titled βC++ Vs Pythonβ- tuples and lists in Python can store elements of different data types.
# Python Listmy_list = [1, 2, 3]
# Python Tuplemy_tuple = (1, 2, 3)// C++ Arrayint arr[3] = {1, 2, 3};
// C++ Vectorstd::vector<int> vec = {1, 2, 3};Python List = Vector C++ Python Tuple = Array C++
Array vs Tuple
- Tuple = Fixed Size and Immutable
- Array = Fixed Size but Mutable
- Tuple = Can store elements of different types.
- Array = Homogeneous, all elements must be of the same type.
Vector vs List
- Both = dynamic resizing and mutable
- List = Can store elements of different types.
- Vector = Homogeneous, all elements must be of the same type.
Note: Tuple are mutable, thats not mean, that we canβt reassign tuple. When you reassign a tuple variable to new data in Python, the original tuple does not get modified; instead, a new tuple is created, and the variable points to this new tuple. The previous data (the original tuple) is no longer referenced by that variable, so it becomes eligible for garbage collection if no other variables or objects reference it.