In this tutorial, you will learn about the different data types in Python. Data types define the kind of value that a variable can store and the operations that can be performed on that value. Python uses dynamic typing, which means that the data type of a variable is determined at runtime.
Here is Everything You Need to Know
We have here a very crisp and concise detail on the 8 data types. Please remember these are basic building blocks of Python programming. Hence, you must at least go through the optimal detail we have provided here.
1. Boolean Data Type
A boolean is such a data type that almost every programming language has, and so is Python. Boolean in Python can have two values – True or False. These values are constants and can be used to assign or compare boolean values. Follow a simple example given below.
condition = False if condition == True: print("You can continue with the prpgram.") else: print("The program will end here.")
While making boolean conditions in Python, we can skip the explicit comparison in our code. And we’ll still get the same behavior.
condition = False if condition: print("You can continue with the prpgram.") else: print("The program will end here.")
The above code will yield the same output as the previous one due to the below statement
if condition:
is equivalent to,
if condition == True:
Next, an expression in Python can also produce a boolean result.
For example – The expression in a condition block will yield a boolean value. Python creates boolean contexts to evaluate expressions.
Whatever the expression is, Python will use the boolean context to determine its truth value. Since Python has many data types, it will operate with its own rules to find the result in a boolean context.
str = "Learn Python" print( len(str) ) # 12 print( len(str) == 12 ) # True print( len(str) != 12 ) # False
In some cases, the boolean constants “True” and “False” might also act as numbers.
A, B = True + 0, False + 0 print(A, B) # 1 0 print( type(A), type(B) ) # (<class 'int'>, <class 'int'>)
It is evident from the above example that True is 1 and the value of False is 0. And they will turn into numbers during arithmetic operations.
2. Number Data Type in Python
Numbers are one of the most prominent Python data types. Unlike many languages which have only integers and floats, Python introduces complex as a new type of numbers.
Here are a few points for you to ponder.
- The numbers in Python are classified using the following keywords.
- int, float, and complex.
- Python has a built-in function type() to determine the data type of a variable or the value.
- Another built-in function
isinstance()
is there for testing the type of an object. - In Python, we can add a “j” or “J” after a number to make it imaginary or complex.
Example.
num = 2 print("The number (", num, ") is of type", type(num)) num = 3.0 print("The number (", num, ") is of type", type(num)) num = 3+5j print("The number ", num, " is of type", type(num)) print("The number ", num, " is complex number?", isinstance(3+5j, complex))
#Output The number ( 2 ) is of type <class 'int'> The number ( 3.0 ) is of type <class 'float'> The number (3+5j) is of type <class 'complex'> The number (3+5j) is complex number? True
- To form a complex number, we can even use the type as a constructor. See the example below.
print( complex(1.2,5)) #(1.2+5j)
- Integers in Python don’t have any size limitation as long as the required memory is available.
num = 1234567890123456789 print( num.bit_length() ) # 61 print( num ) # 1234567890123456789 num=1234567890123456789123456789012345678912345678901234567891234567890123456789 print( num.bit_length() ) # 250 print( num ) # 1234567890123456789123456789012345678912345678901234567891234567890123456789
- A float-type number can have precision up to 15 decimal places.
import sys print( sys.float_info ) # sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) print( sys.float_info.dig ) # 15
3. Python Strings Data Type
A string is treated as a sequence in Python. It is made up of one or more characters enclosed in quotes. Any letter, number, or symbol can also be part of a string. Another concept related to string is Python multiline string which requires a triple quotation mark at the start and one at the end.
str = 'A string wrapped in single quotes' print( str ) # 'A string wrapped in single quotes' str = "A string enclosed within double quotes" print( str ) # 'A string enclosed within double quotes' str = """A multiline string starts and ends with a triple quotation mark.""" print( str ) # 'A multiline string\nstarts and ends with\na triple quotation mark.'
Also, the strings in Python are immutable. It means the memory will be allocated once and re-used thereafter.
A = 'Python3' print( id(A) ) # 140186214284656 B = A print( id(B) ) # 140186214284656
You can see the second string shares the same address as the first one does.
Python has two popular versions, namely 2.7 and 3.4. Most programmers around the globe use either of them. The strings in Python 2 are by default non-Unicode (ASCII) but also have support for Unicode.
On the other hand, Python 3 strings are all Unicode (UTF-8).
Strings in Python 2.
print(type('Python String')) # <type 'str'> print(type(u'Python Unicode String')) # <type 'unicode'>
Strings in Python 3.
print(type('Python String')) # <class 'str'> print(type(u'Python Unicode String')) # <class 'str'>
Python allows slicing strings using a special square-bracket syntax to extract a substring. See the example below.
str = "Learn Python" first_5_chars = str[0:5] print(first_5_chars) # Learn substr_from_2_to_5 = str[1:5] print(substr_from_2_to_5) # earn substr_from_6_to_end = str[6:] print(substr_from_6_to_end) # ython last_2_chars = str[-2:] print(last_2_chars) # on first_2_chars = str[:2] print(first_2_chars) # Le two_chars_before_last = str[-3:-1] print(two_chars_before_last) # ho
4. Bytes Data Type in Python
The byte is an immutable type in Python. It can store a sequence of bytes (each 8-bit) ranging from 0 to 255. Similar to an array, we can fetch the value of a single byte by using the index. But we can not modify the value.
Here are a few differences between a byte and a string.
- Byte objects contain a sequence of bytes whereas the strings store a sequence of characters.
- The bytes are machine-readable objects whereas the strings are just in human-readable form.
- Bytes are machine-readable and can be directly stored on the disk whereas strings need to be encoded before writing them to the disk.
# Make an empty bytes object (8-bit bytes) empty_object = bytes(16) print(type(empty_object)) # <class 'bytes'> print(empty_object) # b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
One scenario, where bytes matter is when carrying out I/O operations with buffering enabled. For example, we have a program that is continuously receiving data over the network. It parses the date after waiting for the message headers and terminators to appear in the stream. It keeps appending the incoming bytes to a buffer.
With Python byte object, it is easy to program the above scenario using the below pseudo code.
buf = b'' while message_not_complete(buf): buf += read_from_socket()
In the later sections of this tutorial, we’ll see the byte-to-string conversion and vice-versa.
5. Python Lists Data Type
Python list is an ordered sequence, similar to an array but can hold different types of objects. It is very flexible and supports dynamic sizing. The index in a list begins with a zero position. Here are some more points on it.
- A list is a heterogeneous collection of items of varied data types. For example, a list object can store the files in a folder, or the employee data in a company, etc.
- Lists in Python are easy to create by placing elements inside square brackets separated by commas.
assorted_list = [True, False, 1, 1.1, 1+2j, 'Learn', b'Python'] first_element = assorted_list[0] print(first_element) # True print(assorted_list) # [True, False, 1, 1.1, (1+2j), 'Learn', b'Python'] for item in assorted_list: print(type(item)) """ <class 'bool'> <class 'bool'> <class 'int'> <class 'float'> <class 'complex'> <class 'str'> <class 'bytes'> """
- List objects are mutable. Python allows modifying a list or its elements via assignments and through the built-in list methods.
simpleton = ['Learn', 'Python', '2'] print( id(simpleton) ) # 56321160 print( simpleton ) # ['Learn', 'Python', '2'] simpleton[2] = '3' print( id(simpleton) ) # 56321160 print( simpleton ) # ['Learn', 'Python', '3']
- Interestingly, a list can contain another list. Such a list is called a nested list in Python.
nested = [[1,1,1], [2,2,2], [3,3,3]] for items in nested: for item in items: print(item, end=' ') # 1 1 1 2 2 2 3 3 3
6. Tuples Data Type in Python
A Python tuple is a heterogeneous collection of objects separated by commas. It means objects of different data types can co-exist in a tuple. The tuple and a list are somewhat similar as they share the following traits.
- Both objects are a type of ordered sequence.
- Each of them allows indexing and repetition.
- Nesting is permitted.
- They can store values of different types.
Below are some basic Python tuple examples.
# Defining a tuple without any element pure_tuple = () print (pure_tuple) # Output- () # Creating a tuple with nested tuples first_tuple = (3, 5, 7, 9) second_tuple = ('learn', 'python 3') nested_tuple = (first_tuple, second_tuple) print(nested_tuple) # Creating a tuple with nested tuples first_tuple = (3, 5, 7, 9) second_tuple = ('learn', 'python 3') nested_tuple = (first_tuple, second_tuple) print(nested_tuple) # Repetition in tuples sample_tuple = ('Python 3',)*3 print(sample_tuple)
How is a tuple different than the list?
Tuples do differ a bit from the list as they are immutable. Python does not allow to modify a tuple after it is created. We can not add or remove any element later. Instead, Python expects us to create a new one with the updated sequence of elements.
Can a tuple have mutable objects as elements?
Here, comes the surprise. Modifying a tuple is forbidden. But Python doesn’t enforce it for the elements. It means we can update them if they are mutable objects.
If you somehow have not read 100+ Python interview questions from our blog, consider checking them out. They are a great resource for anyone who is preparing for a Python interview or wants to improve their Python skills.
7. Python Sets Data Type
A Set is an unordered collection of unique and immutable objects. Its definition starts with enclosing braces { } having its elements separated by commas inside. Amongst all the Python data types, Set is one that supports mathematical operations like union, intersection, symmetric difference, etc.
Python Set is similar to the “Set” in mathematics, hence it can’t have multiple occurrences of the same element.
What makes a Python set better than a list?
Python Set data type has a significant advantage over a list. It implements a highly optimized method that checks whether the container hosts a specific element or not. The mechanism used here is based on a data structure known as a hash table.
To create a set, call the built-in set()
function with a sequence or any iterable object.
sample_set = set("Python data types") print( type(sample_set) ) # <class 'set'> print( sample_set ) # {'e', 'y', 't', 'o', ' ', 'd', 's', 'P', 'p', 'n', 'h', 'a'}
Another simpler way is to specify the elements enclosed in curly braces {}.
another_set = {'red', 'green', 'black'} print( type(another_set) ) # <class 'set'> print( another_set) # {'red', 'green', 'black'}
What is a Frozen set in Python?
A frozen set is a processed form of the traditional set. It is immutable and only supports methods and operators that execute without altering the frozen set used in the context.
# An empty frozenset print( frozenset() ) # frozenset() cities = {"New York City", "Saint Petersburg", "London", "Munich", "Paris"} fset = frozenset(cities) print( type(fset) ) # <class 'frozenset'>
8. Dictionaries in Python
A dictionary in Python is an unordered collection of key-value pairs. It’s a built-in mapping type in Python where keys map to values. These key-value pairs provide an intuitive way to store data.
Why need a dictionary?
The dictionary solves the problem of efficiently storing a large data set. Python has made the dictionary object highly optimized for retrieving data.
Python syntax for creating dictionaries uses braces {} where each item appears as a pair of keys and values. The key and value can be of any Python data type.
sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31} print( type(sample_dict) ) # <class 'dict'> print( sample_dict ) # {'mar': 31, 'key': 'value', 'jan': 31, 'feb': 28}
Accessing dictionary elements with keys
Dictionaries act like a database. Here, we don’t use a number to get a particular index value as we do with a list. Instead, we replace it with a key and then use the key to fetch its value.
sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31} print( sample_dict['jan'] ) # 31 print( sample_dict['feb'] ) # 28
Methods to access dictionary elements
Python exposes the following built-in dictionary functions.
- keys() – It isolates the keys from a dictionary.
- values() – It isolates the values from a dictionary.
- items() – It returns the items in a list style of (key, value) pairs.
sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31} print( sample_dict.keys() ) # dict_keys(['mar', 'key', 'jan', 'feb']) print( sample_dict.values() ) # dict_values([31, 'value', 31, 28]) print( sample_dict.items() ) # dict_items([('mar', 31), ('key', 'value'), ('jan', 31), ('feb', 28)])
Modifying a dictionary (Add/update/delete)
Since the dictionary object is mutable, we can call add, update, and delete operations on a dictionary object. See the below example for more clarity on how to modify a dictionary.
sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31} sample_dict['feb'] = 29 print( sample_dict ) # {'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29} sample_dict.update({'apr':30}) print( sample_dict ) # {'apr': 30, 'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29} del sample_dict['key'] print( sample_dict ) # {'apr': 30, 'mar': 31, 'jan': 31, 'feb': 29}
Apart from learning about the data types, you should also know the different operators in Python. Furthermore, check out one of our recent additions about the xor operator in Python.
Conclusion
This tutorial covered the various Python data types and tried to explain each of them with examples. You may find all the relevant information here which can be useful for you in developing Python programs.
If you find something new to learn today, then do share it with others. And, follow us on our social media accounts to see more such tutorials.
Best,
TechBeamers