Python figures out the type of your data on its own. You just assign a value, and Python decides whether it is an integer, a string, a list, or something else. That is called dynamic typing, and it is one of the reasons Python feels simpler than languages like C or Java.
But "simpler" does not mean you can ignore types. Mixing them up is one of the most common sources of bugs for beginners. This guide walks through every built-in data type with tested code, then shows you how to convert between them when you need to.
Numeric Types In Python
Python has three numeric types. You will use int and float in almost every program. complex shows up mostly in math and engineering courses.
int (Integer)
Integers are whole numbers with no decimal point. They can be positive, negative, or zero. Unlike C or Java, Python integers have no fixed size limit. They grow as large as your memory allows, so you will never see an overflow error.
# Integer Data Type
age = 25
temperature = -10
zero = 0
print("Age:", age)
print("Temperature:", temperature)
print("Zero:", zero)
print("Type:", type(age))
Output:
Age: 25 Temperature: -10 Zero: 0 Type: <class 'int'>
float (Floating-Point Number)
Floats store numbers with a decimal point. Python uses 64-bit double-precision floating point internally, which gives you about 15 to 16 significant digits of precision.
# Float Data Type
price = 9.99
pi = 3.14159
negative = -2.5
print("Price:", price)
print("Pi:", pi)
print("Negative:", negative)
print("Type:", type(price))
Output:
Price: 9.99 Pi: 3.14159 Negative: -2.5 Type: <class 'float'>
One thing to watch out for: floating-point math is not always exact. For example, 0.1 + 0.2 gives 0.30000000000000004, not 0.3. This is not a Python bug. It happens in every language that uses binary floating point. If you need exact decimal math, use the decimal module.
complex (Complex Number)
A complex number has a real part and an imaginary part. In math you write the imaginary unit as i, but Python uses j instead.
# Complex Number Data Type
z = 5 + 3j
print("Complex number:", z)
print("Real part:", z.real)
print("Imaginary part:", z.imag)
print("Type:", type(z))
Output:
Complex number: (5+3j) Real part: 5.0 Imaginary part: 3.0 Type: <class 'complex'>
Sequence Types In Python
Sequence types hold items in order. You can access any item by its position (index), and you can slice out a range of items. The three main sequence types are strings, lists, and tuples.
str (String)
Strings hold text. You can create them with single quotes, double quotes, or triple quotes for multi-line text. Strings are immutable, meaning you cannot change a character in place. Any operation that looks like it changes a string actually creates a new one.
# String Data Type
empty = ""
single = 'Hello'
double = "World"
triple = """This is
a multi-line string."""
print("Concatenation:", single + " " + double)
print("Repetition:", "Ha" * 3)
print("Length of empty string:", len(empty))
print("First character:", single[0])
print("Slice:", single[1:4])
Output:
Concatenation: Hello World Repetition: HaHaHa Length of empty string: 0 First character: H Slice: ell
list
A list is the most flexible built-in collection. It can hold items of any type, and you can add, remove, or change items after you create it. That makes lists mutable.
# List Data Type
fruits = ["apple", "banana", "cherry", "date"]
print("Original list:", fruits)
print("First item:", fruits[0])
print("Slice [1:3]:", fruits[1:3])
fruits[1] = "blueberry"
fruits.append("elderberry")
fruits.remove("cherry")
print("After changes:", fruits)
Output:
Original list: ['apple', 'banana', 'cherry', 'date'] First item: apple Slice [1:3]: ['banana', 'cherry'] After changes: ['apple', 'blueberry', 'date', 'elderberry']
If you want to find a specific item in a list, our guide to finding an index in a Python list covers the main methods.
tuple
A tuple looks like a list but uses parentheses instead of brackets. The key difference is that tuples are immutable. Once you create a tuple, you cannot add, remove, or change its items. Use a tuple when the data should stay fixed, like coordinates or the days of the week.
# Tuple Data Type
colors = ("red", "green", "blue", "yellow")
print("Tuple:", colors)
print("First item:", colors[0])
print("Slice [1:3]:", colors[1:3])
print("Length:", len(colors))
# Tuples are immutable - this would cause an error:
# colors[0] = "purple" # TypeError: 'tuple' object does not support item assignment
Output:
Tuple: ('red', 'green', 'blue', 'yellow')
First item: red
Slice [1:3]: ('green', 'blue')
Length: 4
List vs. Tuple
| Feature | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutable? | Yes | No |
| Speed | Slightly slower | Slightly faster |
| Memory | Uses more | Uses less |
| Best for | Data that changes | Data that stays fixed |
Set Type In Python
A set is an unordered collection with no duplicate items. If you add the same value twice, the set keeps only one copy. Sets are great for removing duplicates and for math operations like union and intersection.
# Set Data Type
numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5}
print("Set (duplicates removed):", numbers)
print("Length:", len(numbers))
numbers.add(7)
numbers.discard(9)
print("After changes:", numbers)
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Union:", a | b)
print("Intersection:", a & b)
Output:
Set (duplicates removed): {1, 2, 3, 4, 5, 6, 9}
Length: 7
After changes: {1, 2, 3, 4, 5, 6, 7}
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Because sets are unordered, you cannot access items by index. If you need both uniqueness and order, use dict.fromkeys() or a list with manual checks.
Mapping Type: dict
A dictionary stores data as key-value pairs. You look things up by key instead of by position, which makes dictionaries very fast for searches. Keys must be immutable (usually strings or numbers), but values can be anything.
# Dictionary Data Type
student = {"name": "Alex", "age": 20, "grade": "A"}
print("Original:", student)
print("Name:", student["name"])
student["school"] = "State University"
student["age"] = 21
del student["grade"]
print("Modified:", student)
Output:
Original: {'name': 'Alex', 'age': 20, 'grade': 'A'}
Name: Alex
Modified: {'name': 'Alex', 'age': 21, 'school': 'State University'}
Boolean Type In Python
The boolean type has exactly two values: True and False. You will see booleans mostly as the result of comparisons and conditions. Under the hood, True is equal to 1 and False is equal to 0, so you can use them in math, though that is rarely a good idea.
# Boolean Data Type
is_student = True
has_graduated = False
print("Is student:", is_student)
print("Has graduated:", has_graduated)
# Booleans from comparisons
x = 10
print("x > 5:", x > 5)
print("x == 3:", x == 3)
print("Type:", type(is_student))
Output:
Is student: True Has graduated: False x > 5: True x == 3: False Type: <class 'bool'>
Binary Types: bytes and bytearray
Binary types work with raw byte-level data. You will run into them when you read files in binary mode, send data over a network, or work with images. bytes is immutable, and bytearray is mutable.
# Binary Data Types
data = bytes([72, 101, 108, 108, 111])
print("bytes:", data)
mutable_data = bytearray([72, 101, 108, 108, 111])
mutable_data[0] = 74 # Change 'H' to 'J'
print("bytearray after change:", mutable_data)
print("Type of data:", type(data))
print("Type of mutable_data:", type(mutable_data))
Output:
bytes: b'Hello' bytearray after change: bytearray(b'Jello') Type of data: <class 'bytes'> Type of mutable_data: <class 'bytearray'>
You probably will not need these in a first Python course, but they become important once you start working with files and APIs.
How To Check A Variable's Type
If you are ever unsure what type a variable holds, use the built-in type() function. It is especially handy when debugging.
# Checking data types with type()
age = 25
price = 9.99
name = "Alex"
scores = [90, 85, 92]
point = (3, 4)
info = {"key": "value"}
flag = True
print(type(age))
print(type(price))
print(type(name))
print(type(scores))
print(type(point))
print(type(info))
print(type(flag))
Output:
<class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'tuple'> <class 'dict'> <class 'bool'>
You can also use isinstance() to check whether a value is a specific type. The difference is that isinstance() returns True or False, which makes it better inside if statements:
age = 25
print(isinstance(age, int)) # True
print(isinstance(age, float)) # False
When To Use Each Data Type
Knowing the types is one thing. Picking the right one for the job is another. Here is a quick reference:
| Situation | Best type | Why |
|---|---|---|
| Whole numbers (count, age, score) | int | No decimal part needed, unlimited size |
| Numbers with decimals (price, distance) | float | Stores decimal values |
| Engineering math with imaginary numbers | complex | Handles real + imaginary parts |
| Text, names, messages | str | Built for text operations |
| A collection you will change often | list | Mutable, easy to add and remove items |
| A collection that should not change | tuple | Immutable, slightly faster |
| Remove duplicates or do set math | set | Automatic deduplication, fast lookups |
| Look up values by a key | dict | Key-value pairs, very fast search |
| True/false conditions | bool | Used in if/else and while loops |
| Raw file or network data | bytes / bytearray | Works at the byte level |
Type Conversion In Python
Sometimes you need to turn one data type into another. Maybe you read a number from the user (which comes in as a string) and need to do math with it, or you need to print a number inside a sentence. Python gives you two ways to handle this: implicit conversion, where Python does it for you, and explicit conversion, where you tell Python exactly what to convert.
Implicit Type Conversion
Python automatically converts a smaller or narrower type into a wider one when you mix them in an expression. The most common case is mixing an int with a float. Python promotes the integer to a float so the calculation works without losing precision.
# Implicit Type Conversion
num_int = 10
num_float = 2.5
result = num_int + num_float
print("Integer:", num_int, "->", type(num_int))
print("Float:", num_float, "->", type(num_float))
print("Result:", result, "->", type(result))
Output:
Integer: 10 -> <class 'int'> Float: 2.5 -> <class 'float'> Result: 12.5 -> <class 'float'>
Notice that the result is a float even though one of the inputs was an int. Python made that decision on its own. However, implicit conversion only works between closely related types. If you try to add a string and an integer, Python will not guess what you mean. It will raise a TypeError instead.
Explicit Type Conversion
When Python cannot convert automatically, you do it yourself using built-in functions. Here are the ones you will use most often:
| Function | What it does | Example |
|---|---|---|
int() | Converts to an integer (drops decimals, parses number strings) | int("42") → 42 |
float() | Converts to a float | float(7) → 7.0 |
str() | Converts to a string | str(100) → "100" |
bool() | Converts to True or False | bool(0) → False |
list() | Converts to a list | list("abc") → ['a','b','c'] |
tuple() | Converts to a tuple | tuple([1,2]) → (1, 2) |
set() | Converts to a set (removes duplicates) | set([1,1,2]) → {1, 2} |
dict() | Converts pairs to a dictionary | dict([("a",1)]) → {'a': 1} |
ord() | Character to its ASCII/Unicode code | ord('A') → 65 |
chr() | ASCII/Unicode code to a character | chr(65) → 'A' |
int(), float(), and str()
These are the three you will reach for most. Here is int() in action:
# Explicit Conversion: int()
price_str = "150"
quantity = 3
total = int(price_str) * quantity
print("Total:", total)
# Float to int (drops the decimal part)
temperature = 98.6
print("As integer:", int(temperature))
# Boolean to int
print("True as int:", int(True))
print("False as int:", int(False))
Output:
Total: 450 As integer: 98 True as int: 1 False as int: 0
Notice that int(98.6) gives 98, not 99. It always drops the decimal part. It does not round.
And float() and str():
# Explicit Conversion: float()
whole = 42
text = "3.14"
print("int to float:", float(whole))
print("str to float:", float(text))
print("Type:", type(float(whole)))
Output:
int to float: 42.0 str to float: 3.14 Type: <class 'float'>
# Explicit Conversion: str()
age = 25
pi = 3.14
flag = True
print("Age: " + str(age))
print("Pi: " + str(pi))
print("Flag: " + str(flag))
# Without str(), this would cause a TypeError:
# print("Age: " + age) # TypeError: can only concatenate str to str
Output:
Age: 25 Pi: 3.14 Flag: True
Without str(), the line "Age: " + age would crash with a TypeError, because Python refuses to add a string and an integer together. You can avoid this entirely by using f-strings: f"Age: {age}" handles the conversion for you.
bool()
Python has a simple rule for boolean conversion: zero, empty, and None are False. Everything else is True.
# Explicit Conversion: bool()
print("bool(0):", bool(0))
print("bool(42):", bool(42))
print('bool(""):', bool(""))
print('bool("hello"):', bool("hello"))
print("bool([]):", bool([]))
print("bool([1, 2]):", bool([1, 2]))
print("bool(None):", bool(None))
Output:
bool(0): False
bool(42): True
bool(""): False
bool("hello"): True
bool([]): False
bool([1, 2]): True
bool(None): False
Converting Between Collections
You can convert between lists, tuples, sets, and dictionaries. This is useful when you need to remove duplicates (convert to a set) or when a function expects a specific type.
# Converting between sequences
text = "Python"
chars = list(text)
print("String to list:", chars)
numbers = [3, 1, 4, 1, 5]
unique = set(numbers)
print("List to set:", unique)
pair = (("name", "Alex"), ("age", 20))
info = dict(pair)
print("Tuples to dict:", info)
Output:
String to list: ['P', 'y', 't', 'h', 'o', 'n']
List to set: {1, 3, 4, 5}
Tuples to dict: {'name': 'Alex', 'age': 20}
ord() and chr()
ord() gives you the Unicode code point of a character, and chr() goes the other way. These are useful in encryption exercises and when working with character math.
# ord() and chr() conversions
letter = 'A'
code = ord(letter)
print(f"ord('{letter}') = {code}")
back = chr(code)
print(f"chr({code}) = '{back}'")
# ASCII table sample
for c in "Hello":
print(f" '{c}' -> {ord(c)}")
Output:
ord('A') = 65
chr(65) = 'A'
'H' -> 72
'e' -> 101
'l' -> 108
'l' -> 108
'o' -> 111
Base Conversions (Binary, Octal, Hex)
The int() function takes an optional second argument: the base of the number system. This lets you convert binary, octal, and hexadecimal strings into regular integers. Python also has bin(), oct(), and hex() for going the other direction.
# Base conversions
binary_str = "1010"
octal_str = "17"
hex_str = "1A"
print("Binary '1010' to int:", int(binary_str, 2))
print("Octal '17' to int:", int(octal_str, 8))
print("Hex '1A' to int:", int(hex_str, 16))
# Going the other way
num = 26
print(f"\n{num} in binary: {bin(num)}")
print(f"{num} in octal: {oct(num)}")
print(f"{num} in hex: {hex(num)}")
Output:
Binary '1010' to int: 10 Octal '17' to int: 15 Hex '1A' to int: 26 26 in binary: 0b11010 26 in octal: 0o32 26 in hex: 0x1a
Converting User Input
This is where most beginners hit their first type error. The input() function always returns a string, even if the user types a number. You have to convert it yourself before doing any math.
# Common mistake: forgetting to convert input
# input() always returns a string
age_str = "25" # simulating input("Enter your age: ")
# This would fail: age_str + 1 -> TypeError
age = int(age_str)
next_year = age + 1
print(f"You are {age}. Next year you will be {next_year}.")
# Works with float too
price_str = "19.99"
price = float(price_str)
tax = price * 0.08
print(f"Price: ${price}, Tax: ${tax:.2f}, Total: ${price + tax:.2f}")
Output:
You are 25. Next year you will be 26. Price: $19.99, Tax: $1.60, Total: $21.59
Implicit vs. Explicit: A Quick Comparison
| Feature | Implicit | Explicit |
|---|---|---|
| Who does it? | Python, automatically | You, with a function call |
| When does it happen? | When mixing related types (int + float) | Whenever you call int(), str(), etc. |
| Risk of data loss? | Low (widens the type) | Possible (float to int drops decimals) |
| Can it fail? | Rarely | Yes, if the value cannot be converted |
Common Mistakes With Data Types In Python
Most Python bugs for beginners come down to data types. Here are the ones we see over and over, and how to avoid them.
- Adding a string and a number without converting.
"Score: " + 95gives aTypeError. Usestr(95)or an f-string:f"Score: {95}". - Forgetting that
input()returns a string.age = input("Age: ")gives you a string. You needint(age)before doing math with it. - Trying to change a tuple.
colors[0] = "purple"fails because tuples are immutable. If you need to change items, use a list. - Using
int()on a non-numeric string.int("hello")raises aValueError. Always check or clean the input first. - Confusing
=and==.=assigns a value.==compares two values. Using the wrong one in an if statement is a common and frustrating bug. - Assuming
int()rounds.int(3.9)gives3, not4. It always cuts off the decimal part. Useround()if you want rounding. - Changing a list you are looping over. Removing items from a list while looping through it can skip items or crash. Loop over a copy instead:
for item in my_list[:]:
Conclusion
Python's built-in data types cover almost everything a beginner needs: integers and floats for numbers, strings for text, lists and tuples for collections, dictionaries for key-value lookups, sets for unique items, and booleans for conditions. Once you know these, the next step is learning how to convert between them, especially when handling user input or mixing types in a calculation.
Takeaways:
- Python figures out the data type for you (dynamic typing), but you still need to know which type you are working with.
- Lists are mutable, tuples are not. Pick the one that fits your situation.
- Dictionaries store key-value pairs and are one of the most-used types in real Python programs.
input()always returns a string. Convert it withint()orfloat()before doing math.- Implicit conversion happens automatically between related types. For everything else, use
int(),str(),float(), and the other built-in functions. - Use
type()when you are unsure what type a variable holds. It is the fastest way to debug a type error.
Once you are comfortable with data types, the next step is using them in real programs. Loops work with lists and strings constantly, so our guide on how loops work in Python is a good place to go next. And if you run into errors along the way, our article on common Python errors in student assignments covers the ones beginners see most.
If you want one-on-one help as you learn, our online Python tutors work through problems like these with you. And if a graded assignment has you stuck, our team also offers Python assignment help.
Frequently Asked Questions
1. What are the main data types in Python?
Python has several built-in data types grouped into categories: numeric (int, float, complex), sequence (str, list, tuple), mapping (dict), set (set), boolean (bool), and binary (bytes, bytearray). You can check any variable's type with the type() function.
2. What is the difference between a list and a tuple in Python?
Both store ordered collections, but a list is mutable (you can add, remove, or change items) while a tuple is immutable (you cannot change it after creation). Use a list when the data needs to change and a tuple when it should stay fixed.
3. What is type conversion in Python?
Type conversion is the process of changing a value from one data type to another. Python does some conversions automatically (like int to float in math), but for most cases you use functions like int(), float(), and str() to convert explicitly.
4. Why does input() always return a string?
Python's input() function reads whatever the user types as text, because it has no way to know whether you expect a number, a name, or something else. You need to convert it yourself with int() or float() before doing math with it.
5. What is the difference between implicit and explicit type conversion?
Implicit conversion happens automatically when Python can safely widen a type, like turning an int into a float during addition. Explicit conversion is when you call a function like int() or str() to force the change yourself.
6. How do I check the data type of a variable in Python?
Use type(variable) to see the type, or isinstance(variable, int) to check whether it is a specific type. type() is quicker for debugging, and isinstance() works better inside if statements.
