Python Data TypesGet Certified
What Is a Data Type?
A data type tells Python what kind of value something is and what you can do with it. You can add two numbers, join two pieces of text, or loop over the items of a list, but you cannot meaningfully add a number to a list. The data type decides which operations are allowed and how the value is stored and displayed.
In Python every value is an object and every object has a type. You do not declare types. Python decides the type when the value is created, and you can ask for it at any time with the built-in type() function.
- Numeric types:
intfor whole numbers,floatfor decimal numbers, andcomplexfor complex numbers. - Text type:
strfor strings of characters. - Boolean type:
bool, with only two values,TrueandFalse. - None type:
NoneType, whose only value isNone, meaning “no value”. - Collection types:
list,tuple,set,dict, andrange, which hold several values together. - Binary types:
bytesandbytearrayfor raw binary data.
Try It: Finding the Type of a Value
Click Test My Code to see the type of six different values. Then replace the values with your own and run it again.
type() and prints the result. The values are a whole number, a decimal number, a string, a Boolean, None, and a complex number.print(type(42))
print(type(3.14))
print(type("Python"))
print(type(True))
print(type(None))
print(type(2 + 3j))42 has no decimal point, so its type is int. The output is <class 'int'>.3.14 contains a decimal point, so its type is float.str.True is a Boolean value. Its type is bool.None represents the absence of a value. It is the only value of the type NoneType.2 + 3j is a complex number. The letter j marks the imaginary part, so the type is complex.Numeric Types: int, float and complex
An int is a whole number with no decimal point. Python integers have no fixed size limit, so they can grow as large as the memory allows. A float is a number with a decimal point, stored as a 64-bit binary fraction. Because many decimal fractions cannot be written exactly in binary, floats can show tiny rounding differences. This is normal in every programming language and not a Python bug.
- Division
/: always returns a float, even when the result is a whole number. - Floor division
//: divides and rounds the result down to a whole number. - Remainder
%: gives what is left after division. - Power
**: raises a number to a power. - Rounding: use
round(value, digits)to display a float neatly.
Try It: Big Integers and Float Precision
Click Test My Code. Notice how Python handles a huge integer without any trouble, and look carefully at the result of 0.1 + 0.2.
round() hides it.big = 2 ** 100
print(big)
print(7 / 2, 7 // 2, 7 % 2)
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))2 ** 100 raises 2 to the power 100. The result is stored in big and is still an exact int, because Python integers have no size limit.1267650600228229401496703205376, with every digit exact.7 / 2 gives 3.5, 7 // 2 gives 3 because the result is rounded down, and 7 % 2 gives the remainder 1.0.30000000000000004. The numbers 0.1 and 0.2 cannot be stored exactly in binary, so a tiny error appears in the sum.round(..., 2) rounds the sum to two decimal places, so the output is 0.3. Use rounding when you display floats.Strings: The str Type
A string is a sequence of characters written inside single quotes, double quotes, or triple quotes. Python 3 strings hold Unicode text, so they can contain letters from any language and emoji. Each character has a position called an index, starting at 0. A negative index counts from the end, so -1 is the last character.
Strings are immutable, which means a string cannot be changed after it is created. Methods such as upper() do not modify the original. They return a new string.
Try It: Indexing and Immutable Strings
Click Test My Code. The program builds a new string instead of changing the old one.
word = "Python"
print(len(word), word.upper(), word[0], word[-1])
new_word = "J" + word[1:]
print(new_word)
print(word)word = "Python" stores a string of six characters.len(word) is 6, word.upper() returns PYTHON, word[0] is the first character P, and word[-1] is the last character n. The output is 6 PYTHON P n.word[1:] is a slice that starts at index 1 and gives ython. Adding "J" in front creates a brand-new string, "Jython".Jython.Python. Strings are immutable, so the original was never modified.Booleans and Truthiness
The bool type has exactly two values, True and False. Comparisons such as 10 > 5 produce Booleans, and if and while statements use them to make decisions. Booleans are a subtype of integers, so True behaves like 1 and False like 0 in arithmetic.
Python can also treat any value as true or false when a Boolean is needed. This is called truthiness. The following values are falsy: False, None, the numbers 0 and 0.0, and every empty collection or string such as "", [], (), {}, and set(). Almost everything else is truthy.
Try It: Truthy and Falsy Values
Click Test My Code and predict each result before you read the output.
bool() to show how numbers, strings, lists, and None are interpreted as true or false. It then prints two comparisons and adds two Booleans to show that True counts as 1.print(bool(0), bool(1), bool(""), bool("hi"))
print(bool([]), bool([0]), bool(None))
print(10 > 5, 10 == 5)
print(True + True)bool(0) is False, bool(1) is True, an empty string is False, and a non-empty string is True. The output is False True False True.0 is truthy because the list itself is not empty. None is falsy. The output is False True False.10 > 5 is True and 10 == 5 is False, so the output is True False.True counts as 1, so True + True equals 2.Collection Types: list, tuple, set and dict
Collection types store several values under one name. Each one suits a different job:
- list: an ordered, changeable sequence written with square brackets, such as
[1, 2, 3]. It allows duplicates. - tuple: an ordered sequence that cannot be changed, written with parentheses, such as
(3, 4). - set: an unordered collection of unique values written with curly braces, such as
{1, 2, 3}. Duplicates are removed automatically. - dict: a collection of key-value pairs written with curly braces and colons, such as
{"name": "Asha"}. Values are looked up by key. - range: an immutable sequence of numbers, mostly used in
forloops.
Each of these has its own lesson later in this tutorial. For now, focus on recognizing them and knowing what makes them different.
Try It: The Four Main Collections
Click Test My Code. Notice that the set removes the duplicate "apple" while the list keeps it.
fruits = ["apple", "banana", "apple"]
point = (3, 4)
unique = {"apple", "banana", "apple"}
person = {"name": "Asha", "age": 21}
print(type(fruits), type(point), type(unique), type(person))
print(len(fruits), len(unique))
print(person["name"])"apple"."apple" is stored only once.key: value pairs create a dictionary with the keys "name" and "age".<class 'list'> <class 'tuple'> <class 'set'> <class 'dict'>.len() counts the items. The list has 3 items and the set has 2, because duplicates were removed. The output is 3 2.person["name"] returns the value stored under the key "name", so the output is Asha.Mutable and Immutable Types
Data types fall into two groups. Mutable objects can be changed after they are created. Lists, sets, and dictionaries are mutable. Immutable objects cannot be changed. Numbers, strings, Booleans, tuples, and None are immutable. When you seem to change an immutable value, Python actually creates a new object.
This difference matters. Only immutable values can be used as dictionary keys or stored in sets, and a mutable object that is shared between names can change unexpectedly.
Try It: Changing a List and Trying to Change a Tuple
Click Test My Code. The tuple assignment raises an error. A try and except block, which you will study in the error-handling lessons, catches the error so the program can print a friendly message instead of stopping.
TypeError, and the program prints the error message.numbers = [1, 2, 3]
numbers[0] = 99
print("List after change:", numbers)
letters = ("a", "b", "c")
try:
letters[0] = "z"
except TypeError as error:
print("Tuple error:", error)numbers refers to a list of three integers.numbers[0] = 99 replaces the first item. Lists are mutable, so this is allowed.List after change: [99, 2, 3].letters refers to a tuple of three strings.try: tells Python to attempt the indented code and to jump to the matching except block if an error occurs.TypeError.except TypeError as error: catches the error and stores it in the variable error, so the program does not crash.Tuple error: 'tuple' object does not support item assignment.Checking Types with type() and isinstance()
The type() function returns the exact type of a value. The isinstance(value, type) function checks whether a value belongs to a type, and it also accepts subtypes. For this reason isinstance() is the preferred way to check types in real programs. To print only the name of a type, use type(value).__name__.
Try It: Looping Over Mixed Values
Click Test My Code and look at the True row. Booleans count as integers in Python, which can be surprising.
isinstance() considers it an integer.values = [10, 3.5, "text", True, None, [1, 2]]
for v in values:
print(v, "->", type(v).__name__, isinstance(v, int))None, and another list. A list can store values of different types.for loop takes the items one at a time and stores each one in v. The indented line below runs once per item.type(v).__name__ gives the type’s name, and isinstance(v, int) returns True or False. The output has six lines. The values 10 and True give True, because bool is a subtype of int. The other four values give False.Reading Input: Everything Starts as a String
The input() function always returns a str, even when the user types digits. To calculate with the value you must convert it to a number first. Converting between types is the subject of the next lesson, so here you only need to notice the difference between the text "41" and the number 41.
Try It: The Type of Input
The Program Input box is already filled with 41. Click Run Code straight away, then try another number.
input() and shows that it is a string. It then converts the text to an integer with int(), adds 1, and prints the result with its new type.value = input("Enter something: ")
print("You typed:", value)
print("Type:", type(value))
number = int(value)
print("As a number:", number + 1, type(number))input() reads the first line of the Program Input box and returns it as text. It is stored in value.You typed: 41.<class 'str'>.int(value) converts the text "41" into the number 41. If the text is not a whole number, Python stops with a ValueError.number is an integer, number + 1 equals 42. The output is As a number: 42 <class 'int'>.Tip: When a program behaves strangely, print the value together with its type, for example print(x, type(x)). A number that is secretly a string is one of the most common beginner bugs.
Common Mistakes with Data Types
- Adding a string and a number:
"Age: " + 21raises aTypeError. Convert the number withstr(21)or use an f-string. - Forgetting to convert input:
input()returns text, soinput() + 1fails. Wrap it inint()orfloat(). - Trusting float equality:
0.1 + 0.2 == 0.3isFalse. Compare withround()ormath.isclose(). - Expecting
/to give an integer:6 / 3is2.0, a float. Use//when you need a whole number. - Empty braces:
{}creates an empty dictionary, not an empty set. Useset()for an empty set. - One-item tuples:
(5)is just the number 5. A tuple with one item needs a trailing comma:(5,). - Changing an immutable value: assigning to a character of a string or an item of a tuple raises a
TypeError.
Key Takeaways
- Every value in Python is an object with a type, and
type()reveals it. - The core built-in types are
int,float,complex,str,bool,NoneType,list,tuple,set,dict, andrange. - Python integers have unlimited size, while floats can show small rounding differences.
- Strings, tuples, numbers, and Booleans are immutable. Lists, sets, and dictionaries are mutable.
- Empty values, zero, and
Noneare falsy, and most other values are truthy. boolis a subtype ofint, soTrueequals1in calculations.- Use
isinstance()to check types, and remember thatinput()always returns a string.
Frequently Asked Questions
What are the basic data types in Python?
The basic built-in data types are int, float, and complex for numbers, str for text, bool for True and False, and NoneType for None. Python also has the collection types list, tuple, set, dict, and range, and the binary types bytes and bytearray.
How do I check the data type of a variable in Python?
Use the built-in type() function, for example type(x). It returns the class of the value that x currently refers to. To test whether a value belongs to a type, use isinstance(x, int), which also accepts subtypes.
What is the difference between int and float in Python?
An int is a whole number without a decimal point, and it can be as large as memory allows. A float is a number with a decimal point stored as a 64-bit binary fraction, so it can show tiny rounding differences such as 0.1 + 0.2 giving 0.30000000000000004.
What is the difference between mutable and immutable types?
A mutable object can be changed after it is created, for example a list, set, or dictionary. An immutable object cannot be changed, for example a number, string, tuple, or Boolean. When you seem to modify an immutable value, Python creates a new object instead.
Is a string mutable in Python?
No. Strings are immutable. You cannot assign to a single character of a string. String methods such as upper() or replace() return a new string and leave the original unchanged.
What is None in Python?
None is a special value that represents the absence of a value. It is the only value of the type NoneType. Functions that do not return anything give None, and it is treated as false in conditions.
Why does input() return a string even when I type a number?
The input() function reads text from the user and always returns it as a str, because it cannot know what you intended. To use the value as a number, convert it with int() for whole numbers or float() for decimal numbers.
Is bool a subtype of int in Python?
Yes. True behaves like 1 and False behaves like 0, so True + True equals 2 and isinstance(True, int) is True. Even so, you should use Booleans for yes-or-no values and integers for counting.