Basic Data Types in Python - Real Python
Basic Data Types in Python - Real Python
Table of Contents
Integers
Floating-Point Numbers
Complex Numbers
Strings
Escape Sequences in Strings
Raw Strings
Triple-Quoted Strings
Boolean Type, Boolean Context, and “Truthiness”
Built-In Functions
Math
Type Conversion
Iterables and Iterators
Composite Data Type
Classes, Attributes, and Inheritance
Input/Output
Variables, References, and Scope
Miscellaneous
Conclusion
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the
written tutorial to deepen your understanding: Basic Data Types in Python
Now you know how to interact with the Python interpreter and Improve
execute Your
Python code. It’s time to dig into the Python
Python
l Fi t i di
https://realpython.com/python-data-types/
i f th b i d t t th t b ilt i t P th 1/15
9/15/2020 Basic Data Types in Python – Real Python
language. First up is a discussion of the basic data types that are built into Python.
Here’s what you’ll learn in this tutorial:
You’ll learn about several basic numeric, string, and Boolean types that are built into Python. By the end of this
tutorial, you’ll be familiar with what objects of these types look like, and how to represent them.
You’ll also get an overview of Python’s built-in functions. These are pre-written chunks of code you can call to
do useful things. You have already seen the built-in print() function, but there are many others.
Email Address
Remove ads
Integers
In Python 3, there is e ectively no limit to how long an integer value can be. Of course, it is constrained by the amount
of memory your system has, as are all things, but beyond that an integer can be as long as you need it to be:
Python >>>
>>> print(123123123123123123123123123123123123123123123123 + 1)
123123123123123123123123123123123123123123123124
Python interprets a sequence of decimal digits without any prefix to be a decimal number:
Python >>>
>>> print(10)
10
The following strings can be prepended to an integer value to indicate a base other than 10:
For example:
Python >>>
>>> print(0x10)
16
>>> print(0b10)
2
For more information on integer values with non-decimal bases, see the following Wikipedia sites: Binary, Octal, and
Hexadecimal.
The underlying type of a Python integer, irrespective of the base used to specify it, is called int:
Python >>>
>>> 10
10
>>> 0x10
16
>>> 0b10
2
Many of the examples in this tutorial series will use this feature.
Note that this does not work inside a script file. A value appearing on a line by itself in a script file will not do
anything.
Floating-Point Numbers
The float type in Python designates a floating-point number. float values are specified with a decimal point.
Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific
notation:
Python >>>
>>> 4.2
4.2
>>> type(4.2)
<class 'float'>
>>> 4.
4.0
Improve Your Python
https://realpython.com/python-data-types/ 3/15
9/15/2020 Basic Data Types in Python – Real Python
>>> .2
0.2
>>> .4e7
4000000.0
>>> type(.4e7)
<class 'float'>
>>> 4.2e-4
0.00042
>>> 1.79e308
1.79e+308
>>> 1.8e308
inf
The closest a nonzero number can be to zero is approximately 5.0 ⨉ 10-324. Anything closer to zero than that is
e ectively zero:
Python >>>
>>> 5e-324
5e-324
>>> 1e-325
0.0
Floating point numbers are represented internally as binary (base-2) fractions. Most decimal fractions cannot
be represented exactly as binary fractions, so in most cases the internal representation of a floating-point
number is an approximation of the actual value. In practice, the di erence between the actual value and the
represented value is very small and should not usually cause significant problems.
Further Reading: For additional information on floating-point representation in Python and the potential
pitfalls involved, see Floating Point Arithmetic: Issues and Limitations in the Python documentation.
Complex Numbers
Complex numbers are specified as <real part>+<imaginary part>j. For example:
Python >>>
>>> 2+3j
(2+3j)
>>> type(2+3j)
<class 'complex'>
https://realpython.com/python-data-types/ 4/15
9/15/2020 Basic Data Types in Python – Real Python
Remove ads
Strings
Strings are sequences of character data. The string type in Python is called str.
Improve Your Python
String literals may be delimited using either single or double quotes. All the characters between the opening delimiter
and matching closing delimiter are part of the string: ...with a fresh 🐍 Python Trick 💌
code snippet every couple of days:
Python >>>
A string in Python can contain as many characters as you wish. The only limit is your machine’s memory resources. A
string can also be empty:
Python >>>
>>> ''
''
What if you want to include a quote character as part of the string itself? Your first impulse might be to try something
like this:
Python >>>
As you can see, that doesn’t work so well. The string in this example opens with a single quote, so Python assumes
the next single quote, the one in parentheses which was intended to be part of the string, is the closing delimiter. The
final single quote is then a stray and causes the syntax error shown.
If you want to include either type of quote character within the string, the simplest way is to delimit the string with the
other type. If a string is to contain a single quote, delimit it with double quotes and vice versa:
Python >>>
You can accomplish this using a backslash (\) character. A backslash character in a string indicates that one or more
characters that follow it should be treated specially. (This is referred to as an escape sequence, because the backslash
causes the subsequent character sequence to “escape” its usual meaning.)
Send
Specifying a backslash in front of the quote character in a string “escapes” it and causes Python
Python Tricks » its usual
to suppress
special meaning. It is then interpreted simply as a literal single quote character:
Python >>>
Python >>>
The following is a table of escape sequences which cause Python to suppress the usual special interpretation of a
character in a string:
\' Terminates string with single quote opening delimiter Literal single quote (') character
\" Terminates string with double quote opening delimiter Literal double quote (") character
Ordinarily, a newline character terminates line input. So pressing Enter ↩ in the middle of a string will cause Python
to think it is incomplete:
Python >>>
>>> print('a
To break up a string over more than one line, include a backslash before each newline, and the newlines will be
ignored:
Improve Your Python
Python >>>
https://realpython.com/python-data-types/ 6/15
9/15/2020 Basic Data Types in Python – Real Python
Python >>>
>>> print('a\
... b\
... c')
abc
Python >>>
>>> print('foo\\bar')
foo\bar
Next, suppose you need to create a string that contains a tab character in it. Some text editors may allow you to insert
Email Address
a tab character directly into your code. But many programmers consider that poor practice, for several reasons:
The computer can distinguish between a tab character and a sequence of space characters, but you can’t. To a
Send Python Tricks »
human reading the code, tab and space characters are visually indistinguishable.
Some text editors are configured to automatically eliminate tab characters by expanding them to the
appropriate number of spaces.
Some Python REPL environments will not insert tabs into code.
In Python (and almost all other common computer languages), a tab character can be specified by the escape
sequence \t:
Python >>>
>>> print('foo\tbar')
foo bar
The escape sequence \t causes the t character to lose its usual meaning, that of a literal t. Instead, the combination is
interpreted as a tab character.
Here is a list of escape sequences that cause Python to apply special meaning instead of interpreting literally:
https://realpython.com/python-data-types/ 7/15
9/15/2020 Basic Data Types in Python – Real Python
Examples:
Python >>>
>>> print("a\tb")
a b
>>> print("a\141\x61")
aaa
>>> print("a\nb")
a Improve Your Python
b
>>> print('\u2192 \N{rightwards arrow}') ...with a fresh 🐍 Python Trick 💌
→ → code snippet every couple of days:
Email Address
This type of escape sequence is typically used to insert characters that are not readily generated from the keyboard or
are not easily readable or printable.
Send Python Tricks »
Raw Strings
A raw string literal is preceded by r or R, which specifies that escape sequences in the associated string are not
translated. The backslash character is le in the string:
Python >>>
>>> print('foo\nbar')
foo
bar
>>> print(r'foo\nbar')
foo\nbar
>>> print('foo\\bar')
foo\bar
>>> print(R'foo\\bar')
foo\\bar
Triple-Quoted Strings
There is yet another way of delimiting strings in Python. Triple-quoted strings are delimited by matching groups of
three single quotes or three double quotes. Escape sequences still work in triple-quoted strings, but single quotes,
double quotes, and newlines can be included without escaping them. This provides a convenient way to create a
string with both single and double quotes in it:
Python >>>
>>> print('''This string has a single (') and a double (") quote.''')
This string has a single (') and a double (") quote.
Because newlines can be included without escaping them, this also allows for multiline strings:
Python >>>
>>> print("""This is a
string that spans
across several lines""")
This is a
string that spans
across several lines
You will see in the upcoming tutorial on Python Program Structure how triple-quoted strings can be used to add an
explanatory comment to Python code.
Improve Your Python
https://realpython.com/python-data-types/ 8/15
9/15/2020 Basic Data Types in Python – Real Python
Python >>>
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
As you will see in upcoming tutorials, expressions in Python are o en evaluated in Boolean context, meaning they are
You will learn more about evaluation of objects in Boolean context when you encounter logical operators in the
upcoming tutorial on operators and expressions in Python. Send Python Tricks »
Built-In Functions
The Python interpreter supports many functions that are built-in: sixty-eight, as of Python 3.6. You will cover many of
these in the following discussions, as they come up in context.
For now, a brief overview follows, just to give a feel for what is available. See the Python documentation on built-in
functions for more detail. Many of the following descriptions refer to topics and concepts that will be discussed in
future tutorials.
Math
Function Description
Type Conversion
Function Description
https://realpython.com/python-data-types/ 9/15
9/15/2020 Basic Data Types in Python – Real Python
Function
chr() Returns string representation of character given by integer argument
Description
type() Returns the type of an object or creates a new type object Send Python Tricks »
enumerate() Returns a list of tuples containing indices and values from an iterable
bytearray() Improve
Creates and returns an object of the bytearray Your Python
class
https://realpython.com/python-data-types/ 10/15
9/15/2020 Basic Data Types in Python – Real Python
Function
bytes()
Description
Creates and returns a bytes object (similar to bytearray, but immutable)
Email Address
Classes, Attributes, and Inheritance
Function Description Send Python Tricks »
super() Returns a proxy object that delegates method calls to a parent or sibling class
Input/Output
Function Description
Function Description
globals() Returns a dictionary representing the current global symbol table
locals() Updates and returns a dictionary representing current local symbol table
Conclusion
In this tutorial, you learned about the built-in data types and functions Python provides.
The examples given so far have all manipulated and displayed only constant values. In most programs, you are
usually going to want to create objects that change in value as the program executes.
Take the Quiz: Test your knowledge with our interactive “Basic Data Types in Python” quiz. Upon
completion you will receive a score so you can track your learning progress over time:
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the
written tutorial to deepen your understanding: Basic Data Types in Python
🐍 Python Tricks
Improve💌
Your Python
https://realpython.com/python-data-types/ 12/15
9/15/2020 Basic Data Types in Python – Real Python
Get a short & sweet Python Trick delivered to your inbox every couple of
days. No spam ever. Unsubscribe any time. Curated by the Real Python
team.
Email Address
John is an avid Pythonista and a member of the Real Python tutorial team.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who
worked on this tutorial are:
Improve
Level Up Your Python SkillsYour
» Python
https://realpython.com/python-data-types/ 13/15
9/15/2020 Basic Data Types in Python – Real Python
Real Python Comment Policy: The most useful comments are those written with the goal of learning
from or helping out other readers—a er reading the whole article and all the earlier comments.
Complaints and insults generally won’t make the cut here. Improve Your Python
...with
What’s your #1 takeaway or favorite thing you learned? How are you going to put fresh 🐍 Python Trick 💌
youra newfound skills to use?
code snippet every couple of days:
Leave a comment below and let us know.
Email Address
🐍 Python Tricks 💌
Email…
https://realpython.com/python-data-types/ 14/15
9/15/2020 Basic Data Types in Python – Real Python
Email Address
Table of Contents
→ Integers Send Python Tricks »
Floating-Point Numbers
Complex Numbers
Strings
Boolean Type, Boolean Context, and “Truthiness”
Built-In Functions
Conclusion
https://realpython.com/python-data-types/ 15/15