Data Types in Python with Examples

Free python courses

Python data types classify data items. They determine the type of value a variable stores. This helps you write effective and error-free programs.

What are Data Types in Python?

A Python data type defines the type of value a variable can hold. It indicates what operations you can perform on that data. Python automatically understands the data type when you assign a value. You do not need to declare it explicitly.

Here are the main categories of built-in data types in Python:

  • Numeric Types: Used for numbers.
  • Sequence Types: Ordered collections of items.
  • Mapping Type: Stores data as key-value pairs.
  • Set Types: Unordered collections of unique elements.
  • Boolean Type: Represents truth values.
  • None Type: Signifies the absence of a value.

You can check the type of any variable using the built-in type() function. For example:

number = 10
print(type(number)) # Output: <class 'int'>

1. Numeric Data Types

Numeric data types handle numerical values. Python has three primary numeric types:

  • Integers (int): Whole numbers, positive or negative, without decimals. They have unlimited precision.

    Example: age = 25, count = -100
  • Floating-point numbers (float): Numbers with decimal points or in exponential form. They represent real numbers.

    Example: price = 19.99, temperature = 37.5, big_number = 1.23e5 (123000.0)
  • Complex numbers (complex): Numbers with a real and an imaginary part, expressed as a + bj.Example: z = 2 + 3j

2. Sequence Data Types

Sequence data types store ordered collections of elements. They support indexing and slicing.

  • Strings (str): Ordered sequences of characters enclosed in single, double, or triple quotes. Strings are immutable; you cannot change their content after creation.

    Example: name = "Alice", message = 'Hello World'
    Accessing characters: name[0] gives ‘A’.
    Slicing: message[0:5] gives ‘Hello’.
  • Lists (list): Ordered, mutable collections of items enclosed in square brackets []. Lists can hold elements of different data types. You can modify, add, or remove elements.

    Example:
    fruits = ["apple", "banana", "cherry"], mixed_list = [1, "hello", True]
    Modifying a list: fruits.append("grape")
    Accessing elements: fruits[0] gives ‘apple’.
  • Tuples (tuple): Ordered, immutable collections of items enclosed in parentheses (). Tuples are similar to lists but cannot be modified after creation. They are faster than lists for iteration.

    Example: coordinates = (10, 20), rgb_color = (255, 0, 128)
    Accessing elements: coordinates[0] gives 10.

3. Mapping Data Type

  • Dictionaries (dict): Unordered collections of key-value pairs enclosed in curly braces {}. Each key must be unique and immutable. Values can be of any data type. Dictionaries are mutable

    Example: person = {"name": "Bob", "age": 30}
    Accessing values: person["name"] gives ‘Bob’.
    Adding or changing entries: person["city"] = "New York"

4. Set Data Types

Set data types are unordered collections of unique elements. They do not allow duplicate items.

  • Sets (set): Mutable, unordered collections of unique elements enclosed in curly braces {}. You can add or remove elements.

    Example: unique_numbers = {1, 2, 3, 2} (stores as {1, 2, 3})
    Adding an element: unique_numbers.add(4)
  • Frozensets (frozenset): Immutable versions of sets. Once created, you cannot change their content.

    Example: immutable_set = frozenset([1, 2, 3])

5. Boolean Type

  • Booleans (bool): Represent truth values: True or False. They are used in logical operations and control flow.

    Example: is_active = True, has_permission = False
    True evaluates to 1 and False to 0 in numeric contexts.

6. None Type

  • NoneType (None): Represents the absence of a value. It is a special data type with a single value, None.Example: result = None

Mutable vs. Immutable Data Types

Understanding mutability is crucial in Python.

  • Mutable Data Types: You can change the value of these objects after they are created without creating a new object in memory.Examples: Lists, Dictionaries, Sets, Bytearray
    Benefit: Memory efficient for frequent modifications.
  • Immutable Data Types: You cannot change the value of these objects after they are created. Any operation that appears to modify an immutable object actually creates a new object.

    Examples: Integers, Floats, Complex numbers, Booleans, Strings, Tuples, Frozensets, Bytes
    Benefit: Ensures data integrity and can be faster in some scenarios.

Common Uses of Python Data Types

  • Integers and Floats: Perform mathematical calculations, represent quantities, or store measurements.
  • Strings: Handle text data, parse user input, or format messages.
  • Lists: Store collections of items that might change, like items in a shopping cart or a list of user names.
  • Tuples: Store fixed collections of data where immutability is important, such as coordinates or database records.
  • Dictionaries: Store data that requires quick lookups by a unique key, like user profiles or configuration settings.
  • Sets: Store unique items, perform membership tests, or eliminate duplicates from a collection.
  • Booleans: Control program flow with conditional statements (if, else) and loops.
  • None: Indicate that a variable has no value or a function returns nothing.
Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Academy Pro Subscription

Grab 50% off
on Top Courses - Free Trial Available

×
Scroll to Top