Python Central HubSign in

Python Programming

Python Data Types

An introduction to data types in Python.

Understanding Data Types in Python

Data types in Python are a fundamental concept that plays a crucial role in defining the nature of variables and how they behave during operations. Python is a dynamically-typed language, which means that the interpreter can determine the type of a variable at runtime. This flexibility allows for more concise and expressive code. Let's delve into the essential data types in Python.

Diagram:

diagram Python built-in data types mermaid
The main categories of built-in types

Dynamic Typing

Because Python infers types at runtime, the same variable can hold different types over its life — the type belongs to the value, not the variable.

Python
x = 42          # x is now an int
print(type(x))  # <class 'int'>
x = "hello"     # x is now a str — perfectly legal
print(type(x))  # <class 'str'>

Output:

cmd
C:\Users\Your Name> python dynamic.py
<class 'int'>
<class 'str'>

Numeric Data Types

Integers

int

Integers represent whole numbers without any fractional part. They can be positive or negative.

Python
age = 25
population = -1000

or you can use the int() function to convert a string to an integer.

Python
age = int(25)
population = int(-1000)

Floating-Point Numbers

float

Floating-point numbers are used to represent real numbers with a decimal point.

Python
pi = 3.14
temperature = -15.5

or you can use the float() function to convert a string to a floating-point number.

Python
pi = float(3.14)
temperature = float(-15.5)

Complex Numbers

complex

Complex numbers have both a real and an imaginary part.

Python
z = 3 + 4j

or you can use the complex() function to create a complex number.

Python
z = complex(3, 4)

Sequence Types

Strings

str

Strings are sequences of characters and are enclosed in single or double quotes.

Python
name = "John"
message = 'Hello, Python!'

or you can use the str() function to convert a number to a string.

Python
name = str("John")
message = str('Hello, Python!')

Lists

list

Lists are ordered, mutable sequences that can contain elements of different data types.

Python
fruits = ['apple', 'banana', 'orange']
mixed_list = [1, 'two', 3.0, [4, 5]]

or you can use the list() function to convert a tuple to a list.

Python
fruits = list(('apple', 'banana', 'orange'))
mixed_list = list((1, 'two', 3.0, [4, 5]))

Tuples

tuple

Tuples are ordered, immutable sequences. Once created, their elements cannot be changed.

Python
coordinates = (3, 4)
RGB_color = (255, 0, 0)

or you can use the tuple() function to convert a list to a tuple.

Python
coordinates = tuple([3, 4])
RGB_color = tuple([255, 0, 0])

Set Types

Sets

set

Sets are unordered collections of unique elements.

Python
unique_numbers = {1, 2, 3, 4, 5}

or you can use the set() function to create a set.

Python
unique_numbers = set([1, 2, 3, 4, 5])

Mapping Type

Dictionary

dict

Dictionaries are unordered collections of key-value pairs.

Python
person = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'}

or you can use the dict() function to create a dictionary.

Python
person = dict({'name': 'Alice', 'age': 30, 'city': 'Wonderland'})

Boolean Type

Boolean

bool

Boolean values represent truth or falsehood and are used in logical operations.

Python
is_raining = True
has_pet = False

or you can use the bool() function to convert a number to a boolean.

Python
is_raining = bool(1)
has_pet = bool(0)

Special Types

None Type

NoneType

The None type represents the absence of a value or a null value.

Python
result = None

Type Conversion

Python allows you to convert between different data types using built-in functions like int(), float(), str(), etc.

Python
num_str = "42"
num_int = int(num_str)

Checking Data Types

You can check the data type of a variable using the type() function.

Python
age = 25
print(type(age))  # <class 'int'>

Operations on Data Types

Different data types support various operations. For example, you can concatenate strings, perform arithmetic operations on numbers, and use logical operators with booleans.

Python
greeting = "Hello, "
name = "Alice"
full_greeting = greeting + name  # Concatenation of strings

Data Type Table

There are many more data types in Python, but the ones listed above are the most commonly used ones. The following table summarizes the data types in Python.

Data Type        DescriptionExample
intIntegerage = 25
floatFloating-point numberpi = 3.14
complexComplex numberz = 3 + 4j
strStringname = "Alice"
listListfruits = ['apple', 'banana', 'orange']
tupleTuplecoordinates = (3, 4)
setSetunique_numbers = {1, 2, 3, 4, 5}
frozensetFrozen setunique_numbers = frozenset({1, 2, 3, 4, 5})
dictDictionaryperson = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'}
boolBooleanis_raining = True
NoneTypeNoneresult = None
rangeRangenumbers = range(1, 10)
bytesBytesdata = b'Hello, Python!'
bytearrayByte arraydata = bytearray(10)
memoryviewMemory viewdata = memoryview(bytes(10))

Mutable vs. Immutable Types

A crucial distinction: some objects can be changed after creation (mutable), and some cannot (immutable). Trying to change an immutable object creates a new object instead.

Mutable (can change)Immutable (cannot change)
list, dict, set, bytearrayint, float, complex, bool
str, tuple, frozenset, bytes
Python
# Lists are mutable - same object is modified
numbers = [1, 2, 3]
numbers[0] = 99
print(numbers)        # [99, 2, 3]
 
# Strings are immutable - this raises an error
text = "hello"
# text[0] = "H"       # TypeError: 'str' object does not support item assignment

Visualize it

Whether a type can be changed in place is one of the most important things to know about it.

diagram Built-in types grouped by mutability mermaid
Immutable types cannot be changed in place; mutable types can.

Conclusion

Understanding Python's data types is fundamental to writing effective and efficient code. Python's flexibility in handling various data types makes it suitable for a wide range of applications, from simple scripts to complex data analysis and machine learning tasks. As you continue your journey in Python programming, a solid grasp of data types will empower you to manipulate and process data effectively.

Explore more Python concepts and practical examples in our tutorials on Python Central Hub!


Try it: Data Types Exercises

Exercise 1 – Identify Data Types

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Working with Different Types

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Collections

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did