What are Python’s built-in data types?

26/06/2024 0 By indiafreenotes

Python offers a variety of built-in data types that are designed to handle different kinds of data efficiently.

Numeric Types:

  1. int (Integer):
    • Represents whole numbers without a fractional component.
    • Example: a = 10
  2. float (Floating Point):
    • Represents real numbers with a fractional component.
    • Example: b = 10.5
  3. complex (Complex Number):
    • Represents complex numbers with a real and an imaginary part.
    • Example: c = 3 + 4j

Sequence Types:

  1. str (String):
    • Represents a sequence of characters (text).
    • Example: s = “Hello”
  2. list (List):
    • Represents an ordered collection of items, which can be of mixed types.
    • Example: l = [1, 2, 3, “four”]
  3. tuple (Tuple):
    • Represents an ordered collection of items, which can be of mixed types.
    • Example: t = (1, 2, 3, “four”)
  4. range:
    • Represents an immutable sequence of numbers, commonly used for looping a specific number of times in for loops.
    • Example: r = range(5)

Mapping Type:

  1. dict (Dictionary):
    • Represents a collection of key-value pairs.
    • Example: d = {“key1”: “value1”, “key2”: “value2”}

Set Types:

  1. set:
    • Represents an unordered collection of unique items.
    • Example: s = {1, 2, 3, 4}
  • frozenset:
    • Represents an immutable version of a set.
    • Example: fs = frozenset([1, 2, 3, 4])

Boolean Type:

  • bool:
    • Represents Boolean values: True and False.
    • Example: flag = True

Binary Types:

  • bytes:
    • Represents an immutable sequence of bytes.
    • Example: b = b’hello’
  • bytearray:
    • Represents a mutable sequence of bytes.
    • Example: ba = bytearray(b’hello’)
  • memoryview:
    • Represents a view object that exposes the memory of another binary object (like bytes or bytearray) without copying.
    • Example: mv = memoryview(b’hello’)

None Type:

  • NoneType:
    • Represents the absence of a value or a null value.
    • Example: n = None

Examples and Usage:

Numeric Types:

a = 10        # int

b = 10.5      # float

c = 3 + 4j    # complex

Sequence Types:

s = “Hello”             # str

l = [1, 2, 3, “four”]   # list

t = (1, 2, 3, “four”)   # tuple

r = range(5)            # range

Mapping Type:

d = {“key1”: “value1”, “key2”: “value2”}   # dict

Set Types:

s = {1, 2, 3, 4}                     # set

fs = frozenset([1, 2, 3, 4])         # frozenset

Boolean Type:

flag = True   # bool

Binary Types:

b = b’hello’              # bytes

ba = bytearray(b’hello’)  # bytearray

mv = memoryview(b’hello’) # memoryview

None Type:

n = None  # NoneType