DEV Community

Maksym
Maksym

Posted on

Data types in Python

Python has several built-in data types that serve different purposes. Here's a comprehensive breakdown:

Numeric Types

Integer (int)

  • Whole numbers without decimal points
  • Can be positive, negative, or zero
  • No size limit (limited only by available memory)
age = 25
temperature = -5
Enter fullscreen mode Exit fullscreen mode

Float (float)

  • Numbers with decimal points
  • Uses double precision
price = 19.99
pi = 3.14159
Enter fullscreen mode Exit fullscreen mode

Complex (complex)

  • Numbers with real and imaginary parts
z = 3 + 4j
Enter fullscreen mode Exit fullscreen mode

Sequence Types

String (str)

  • Ordered collection of characters
  • Immutable (cannot be changed after creation)
  • Enclosed in quotes (single, double, or triple)
name = "Alice"
message = 'Hello World'
multiline = """This is a
multiline string"""
Enter fullscreen mode Exit fullscreen mode

List (list)

  • Ordered collection of items
  • Mutable (can be modified)
  • Can contain different data types
fruits = ["apple", "banana", "orange"]
mixed = [1, "hello", 3.14, True]
Enter fullscreen mode Exit fullscreen mode

Tuple (tuple)

  • Ordered collection of items
  • Immutable
  • Defined with parentheses
coordinates = (10, 20)
colors = ("red", "green", "blue")
Enter fullscreen mode Exit fullscreen mode

Mapping Type

Dictionary (dict)

  • Unordered collection of key-value pairs
  • Keys must be immutable and unique
  • Values can be any data type
person = {"name": "John", "age": 30, "city": "New York"}
Enter fullscreen mode Exit fullscreen mode

Set Types

Set (set)

  • Unordered collection of unique items
  • Mutable
  • No duplicate values allowed
unique_numbers = {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

Frozen Set (frozenset)

  • Immutable version of set
immutable_set = frozenset([1, 2, 3, 4])
Enter fullscreen mode Exit fullscreen mode

Boolean Type

Boolean (bool)

  • Represents True or False
  • Subclass of int (True = 1, False = 0)
is_sunny = True
is_raining = False
Enter fullscreen mode Exit fullscreen mode

None Type

None (NoneType)

  • Represents absence of value
  • Often used as default value or placeholder
result = None
Enter fullscreen mode Exit fullscreen mode

Key Characteristics

Mutable vs Immutable:

  • Mutable: list, dict, set (can be modified)
  • Immutable: int, float, str, tuple, frozenset, bool, None (cannot be modified)

Type Checking:

type(42)        # <class 'int'>
isinstance(42, int)  # True
Enter fullscreen mode Exit fullscreen mode

Type Conversion:

int("123")      # 123
str(456)        # "456"
list("hello")   # ['h', 'e', 'l', 'l', 'o']
Enter fullscreen mode Exit fullscreen mode

Understanding these data types is fundamental since they determine what operations you can perform on your data and how Python stores and manipulates information in memory.

Top comments (0)