1. python
  2. /basics
  3. /data-types

The Basics of Python Data Types

The Fundamentals of Data Types in Python

As a relatively flexible language, Python allows us to work with a wide range of data types. According to the official documentation, the primary built-in types include numerics, mappings, sequences, classes, and some exceptions. Naturally, there are many nuances involved but we'll be mostly focusing on an extensive overview.

Numeric Data Types

The core of Python's numerics consists of three distinct numeric types; integers, floating-point numbers, and lastly, complex numbers with their real and imaginary parts.

# Integers
x = 10
y = -5
z = 0
print(type(x)) # Output: <class 'int'>   
print(type(y)) # Output: <class 'int'> 
print(type(z)) # Output: <class 'int'>

# Floating-point numbers
a = 10.5
b = -0.01
c = 0.0

print(type(a)) # Output: <class 'float'> 
print(type(b)) # Output: <class 'float'>
print(type(c)) # Output: <class 'float'>

# Complex numbers
d = 3 + 4j
e = -2 + 3j
f = 0 + 0j
print(type(d)) # Output: <class 'complex'>
print(type(e)) # Output: <class 'complex'>
print(type(f)) # Output: <class 'complex'>

With these numeric data types, we can perform a wide range of mathematical operations, powered by bitwise operators and booleans as a subtype of integers.

Additionally, we can leverage built-in functions like abs() and pow(), to name a few, to carry out more advanced manipulation.

Feel free to check out our Basics of Numbers in Python article and understand the numeric data types in more detail.

Python Strings

When it comes to working with text data, strings in Python represent an immutable sequence of characters. Python supports Unicode characters, giving us the option to work with a wide range of characters from different languages and scripts.

Strings are represented by either single quotes (') or double quotes (").

# String data type
x = "Hello, World!"
y = 'Python programming'

# Character example
character = "a"
print(len(character)) # 1

Bear in mind, that Python doesn't have a separate character data type. Instead, a character in Python is simply a string with a length of one. Additionally, the str keyword represents the str class, which provides a range of methods and functions for working with strings.

Sequence Types in Python

Boiled down, the language gives us the option of using three rudimentary sequence types such as tuples, lists, and range objects. We aim to briefly cover them and understand the nature of how they function.

Lists

Inside lists, we can store an order collection of items, and since they're mutable by nature, we can alter the elements after their initial creation. We can store items of various data types, including numbers, strings, and even nested lists.

list_example = [1, 2, 3, 4, 5]
list_example_two = [10.5, 20.0, 30.1, 40.2]
fruits = ['apple', 'banana', 'cherry']

Moreover, we can utilize built-in methods to alter them, such as adding, or removing elements, and even other useful manipulations. We'll cover the additional methods in a separate article.

# Creating a list
fruits = ['apple', 'banana', 'cherry']

# Adding an element to the list
fruits.append('orange')
print(fruits) # ['apple', 'banana', 'cherry', 'orange']

# Removing an element from the list
fruits.remove('cherry')
print(fruits) # ['apple', 'pear', 'orange']

Tuples

In a similar fashion to lists, tuples store an ordered collection of elements. One of the main differences is that they're immutable and are frequently used when a fixed and unalterable sequence of homogeneous data is necessary, such as for storage within an instance of a set or dictionary.

# Creating a tuple of numbers
numbers = (1, 2, 3, 4, 5)

# Accessing elements in the tuple
second_number = numbers[1]
print(second_number) # 2

# Attempting to modify an element in the tuple (will result in an error)
numbers[1] = 6
print(numbers)
# TypeError: 'tuple' object does not support item assignment

# Creating a tuple of strings
words = ('hello', 'world', 'goodbye')

# Accessing elements in the tuple
second_word = words[1]
print(second_word) # 'world'

Notice that we use parentheses for their syntax, but they're optional and written as so to avoid confusion. What differentiates them is the use of commas to separate the elements.

Range

Mostly, we use the range data type for looping over a sequence of numbers. With range, we can specify the start, stop, and step values of the execution. Below, we can demonstrate that with a basic example using the for loop:

# Create a range of numbers from 0 to 5
p = range(0, 5)
for i in p:
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

Mapping Types - Dictionaries

For now, dictionaries are the only standardized mapping type in Python. As mutable objects, they give us the option to store and retrieve their values. We can create a collection of key-value pairs, where each key maps to a value.

# Create a dictionary
dict_example = {
    "name": "Guido van Rossum",
    "age": 67,
    "city": "Amsterdam"
}

With dictionaries, we store data in a way that makes it easy to look up values based on a specific key. For instance, take a look at a dictionary of employee records, where each employee is represented by a key-value pair.

employees = {
    "John Doe": {
        "age": 30,
        "city": "New York"
    },
    "Jane Doe": {
        "age": 25,
        "city": "Los Angeles"
    }
}

To access the data for a specific employee, we can use the employee's name as the key.

john_doe = employees["John Doe"]
print(john_doe["age"]) # 30
print(john_doe["city"]) # New York

In addition to simply storing data, dictionaries provide a wealth of built-in methods and functions.

Python Set Types

The two main set data types are set and frozenset. The first is a mutable data type in which we can store and change unordered collections of unique values, while the latter is both immutable and hashable, meaning that once the object is created we cannot manipulate its contents.

Set

# Creating a set of unique city names
cities = {'New York', 'London', 'Paris', 'Berlin'}

# Adding an element to the set
cities.add('Tokyo')
print(cities) # {'New York', 'London', 'Paris', 'Berlin', 'Tokyo'}

# Adding a duplicate element to the set (will not be added)
cities.add('London')
print(cities) # {'New York', 'London', 'Paris', 'Berlin', 'Tokyo'}

# Attempting to access elements using indexing (will result in an error)
city = cities[0]
print(city)
# TypeError: 'set' object is not subscriptable

Note that we cannot access elements in a set by their position, as with lists or tuples. Sets don't support indexing and when we attempt to do so, we get a type error as a result.

Final Thoughts

Having a strong grasp of these fundamental concepts can make a huge impact on your ability to write efficient, and well-structured Python programs. Whether you're working with numbers, text, sequences, binary data, or collections of unique values, knowing the strengths and limitations of each data type will help you choose the right tool for your projects.

Additional Resources

Python 3.11.2 Documentation on Built-in Types

Python Built-in Exceptions

Operators in Python