Data Types in Python with Examples

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

Free python courses

What are Data Types in Python?

A Python data type tells you what kind of value a variable holds. It also shows what actions you can do with that data. Python figures out the data type automatically when you give a variable a value. You do not need to state it directly.

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

  • Numbers: These are for numerical values.
  • Sequences: These are ordered collections of items.
  • Mappings: These store data in key-value pairs.
  • Sets: These are unordered collections of unique items.
  • Booleans: These show true or false values.
  • None Type: This means there is no value.

You can check a variable’s type using the type() function. For example:

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

1. Number Data Types

Number data types handle numerical values. Python has three main number types:

Integers (int):

These are whole numbers. They can be positive or negative. They do not have decimals. Integers can be very large or very small.

Example:

age = 25
count = -100
print(type(age))  # Output: <class 'int'>

Floating-point numbers (float):

These are numbers with decimal points. They can also be in a scientific form (like 1.23e5). These numbers show real numbers.

Example:

price = 19.99
temperature = 37.5
big_number = 1.23e5 # This means 1.23 multiplied by 10 to the power of 5 (123000.0)
print(type(price)) # Output: <class 'float'>

Complex numbers (complex):

These numbers have two parts. One is a real part, and the other is an imaginary part. They look like a+bj.

Example:

z = 2 + 3j
print(type(z)) # Output: <class 'complex'>

2. Sequence Data Types

Sequence data types store items in a specific order. You can find individual items by their position. This is called indexing. You can also pick out a range of items, which is called slicing.

Strings (str):

These are ordered groups of characters. You put them in single, double, or triple quotes. Strings cannot be changed after you create them. If you make a change to a string, Python actually makes a new string.

Example:

name = "Alice"
message = 'Hello World'
long_text = """This is a string
that spans multiple lines."""

# Get the first character
print(name[0]) # Output: A

# Get characters from position 0 up to (but not including) 5
print(message[0:5]) # Output: Hello

# Strings cannot be changed directly
# name[0] = 'B' # This would cause an error

Lists (list):

These are ordered collections of items. They are changeable, meaning you can modify them. You put items in lists inside square brackets []. Lists can hold items of different data types. You can change, add, or remove items after the list is made.

Example:

fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "hello", True, 3.14]

# Add an item to the list
fruits.append("grape")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'grape']

# Get the first item
print(fruits[0]) # Output: apple

# Change the second item
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'grape']

Tuples (tuple):

These are ordered collections of items. They are unchangeable, meaning you cannot modify them after you create them. You put items in tuples inside parentheses (). Tuples are like lists, but they are fixed. They are often quicker than lists when you just need to read data.

Example:

coordinates = (10, 20)
rgb_color = (255, 0, 128)

# Get the first item
print(coordinates[0]) # Output: 10

# Tuples cannot be changed
# coordinates[0] = 5 # This would cause an error

3. Mapping Data Type

Mapping data types store data as pairs. Each pair has a “key” and a “value.”

Dictionaries (dict):

These are unordered collections of key-value pairs. You put them in curly braces {}. Each key must be unique. Keys also cannot be changed (like strings or numbers). The values can be any data type. Dictionaries are changeable.

Example:

person = {"name": "Bob", "age": 30, "is_student": False}

# Get a value using its key
print(person["name"]) # Output: Bob

# Add a new item or change an existing one
person["city"] = "New York"
print(person) # Output: {'name': 'Bob', 'age': 30, 'is_student': False, 'city': 'New York'}

# Update an existing value
person["age"] = 31
print(person) # Output: {'name': 'Bob', 'age': 31, 'is_student': False, 'city': 'New York'}

4. Set Data Types

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

Sets (set):

Sets are changeable, unordered collections of unique items. You put them in curly braces {}. You can add or remove items. These are useful for checking if an item is present or for removing repeated items from a list.

Example:

unique_numbers = {1, 2, 3, 2, 4, 1} # Python only keeps unique numbers
print(unique_numbers) # Output: {1, 2, 3, 4}

# Add an item
unique_numbers.add(5)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}

# Remove an item
unique_numbers.remove(2)
print(unique_numbers) # Output: {1, 3, 4, 5}

Frozensets (frozenset):

Frozensets are unchangeable versions of sets. Once you create a frozenset, you cannot change its content. This makes them useful as keys in dictionaries or as items within other sets.

Example:

immutable_set = frozenset([1, 2, 3, 2])
print(immutable_set) # Output: frozenset({1, 2, 3})

# You cannot add or remove items from a frozenset
# immutable_set.add(4) # This would cause an error

5. Boolean Type

Booleans (bool):

Booleans show true or false values: True or False. They are important for making choices in your code. You use them in if statements and loops. In math, Python treats True as 1 and False as 0.

Example:

is_active = True
has_permission = False

print(type(is_active)) # Output: <class 'bool'>

if is_active:
    print("User is active.")
else:
    print("User is inactive.")

print(True + 1)  # Output: 2 (because True is 1)
print(False + 1) # Output: 1 (because False is 0)

6. None Type

NoneType (None):

This means there is no value. It is a special data type with only one value: None. You use None when a variable has nothing assigned to it, or when a function does not return anything.

Example:

result = None
print(type(result)) # Output: <class 'NoneType'>

def greet(name):
    # This function prints something but does not send back a value
    print(f"Hello, {name}!")

returned_value = greet("World")
print(returned_value) # Output: None (because the function didn't return anything)

Changeable vs. Unchangeable Data Types

Knowing if a data type is changeable or unchangeable is key in Python. It changes how your data acts when you modify it.

Changeable Data Types:

You can change the items inside these objects after they are made. Python does not create a new object in memory when you make these changes.

Examples: Lists, Dictionaries, Sets, Bytearray

Benefit: This saves memory. It’s good when you often need to change items.

my_list = [1, 2, 3]
print(f"Original list ID: {id(my_list)}") # This is the list's memory address
my_list.append(4) # Add an item
print(f"Modified list: {my_list}")
print(f"Modified list ID: {id(my_list)}") # The memory address stays the same

Unchangeable Data Types:

You cannot change the items inside these objects after they are made. If you try to “change” an unchangeable object, Python actually creates a new object with the updated value. The old object remains as it was.

Examples: Integers, Floats, Complex numbers, Booleans, Strings, Tuples, Frozensets, Bytes

Benefit: Your data stays safe. It cannot be accidentally changed. This can also make your code faster in some cases.

my_string = "hello"
print(f"Original string ID: {id(my_string)}")
my_string = my_string + " world" # This creates a brand new string object
print(f"Modified string: {my_string}")
print(f"Modified string ID: {id(my_string)}") # The memory address changes

Common Uses of Python Data Types

  • Integers and Floats: Use these for math calculations. Store quantities like the number of books or someone’s age. Use them for measurements like temperature or price.
  • Strings: Handle text data. Get input from users. Make messages or store names and addresses.
  • Lists: Store items that might change. Think of items in a shopping cart or a list of user names.
  • Tuples: Store fixed sets of data. Use them when you need data that won’t change, like map coordinates or color codes (RGB values).
  • Dictionaries: Store data that needs quick lookups by a unique key. Examples are user profiles (like {'username': 'john_doe', 'password': 'abc'}) or settings for a program.
  • Sets: Store unique items. Use them to quickly check if an item is present or to remove repeated items from a list.
  • Booleans: Control how your program runs. Use them with if statements or while loops to make decisions. They show true/false states.
  • None: Show that a variable has no value. Or that a function doesn’t give back any result.
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