Literal Representation of Various Data Types in Python:
Decimal Numbers: Represented directly.
Hexadecimal Numbers: Prefixed with 0x, e.g., 0xff for 255.
Octals:
- In Python 2.x: Added 0, e.g., 0111 represents 111.
- In Python 3.x: Added 0o, e.g., 0o111 represents 111.
Floating Points: Represented directly.
Long Integers:
- Represented directly.
- Optionally, append L at the end, e.g., 1L for 1 long int.
Complex Numbers: Comprise a real number and an imaginary part with a ‘j’, e.g., 6+7j.
Strings: Enclosed in single or triple quotes, e.g., ‘word’ or ”’word”’. Double quotes (“word”) are also valid.
Lists: Defined using square brackets, e.g., [‘abc’, 1, 2, 3].
Tuples: Enclosed in parentheses and separated by commas, e.g., (8, ‘some words’).
Dictionaries (Dicts):
- Enclosed in curly braces.
- Elements consist of key-value pairs separated by a colon.
- Elements are separated by commas.
- Example: {‘name’: ‘Alex’, ‘occupation’: ‘python developer’}.
Difference between tuple and list:
Mutability:
- Tuple: Immutable; cannot be modified after creation.
- List: Mutable; can be modified after creation.
Heterogeneity vs. Homogeneity:
- Tuple: Heterogeneous; elements can be of different data types.
- List: Homogeneous; elements are of the same data type.
Structure vs. Order:
- Tuple: Has structure; elements may have different meanings.
- List: Has order; elements are arranged in a specific sequence.
Tuple = (1,2)
List = [1,2]
Size
x = tuple(range(1000))
y = list(range(1000))
x.__sizeof__() # 8024
y.__sizeof__() # 9088
Permitted operation:
x = [1,2]
y[0] = 3
y = (1,2)
a[0] = 3 // produces an error
Also, it’s important to note that you can’t delete or sort elements in a tuple. However, you can add a new element to both a tuple and a list:
x = (1,2)
y = [1,2]
x += (3,) # (1, 2, 3)
y += [3] # [1, 2, 3]
Usage: since tuples are immutable, you can use them as keys in a dictionary. On the other hand, lists are mutable and cannot be used as dictionary keys. This distinction in usage showcases the practical implications of their immutability.
x = (1,2)
y = [1,2]
z = {x: 1} // OK
c = {y: 1} // error