Data Types in Python Made Simple [+ Examples]

Data types in python

This is the most complete guide to data types in python.

In this in-depth guide, you’ll learn:

1. What are data types in python?

2. Classification (Types) of data types in python

3. Why do we need data types? (why data types is so important)

(Including lots of examples and uses of each data types)

So if you are looking to improve your coding skills like a pro, you’ll really enjoy this post.

Let’s get started!

What are data types in python?

As the name suggests, Data types indicates the different categories of data items (values).

Data types basically represents the type of value stored into a variable (memory location).

The meaning or you can say the definition of data types in general (mathematical view) or in any programming languages are same.

The only difference is, different programming languages consists different types of data types.


Classification of Data Types in Python

Data types are generally classified into the following:

  • Built-in Data Types
  • User defined Data Types

1. Built-in Data Types: Built-in data types are the fundamental data types which are provided or supported by python language.

Or,

In other words:

Built-in data types are the predefined or compiler/interpreter defined data types whose meaning and purpose has already been described for a compiler or interpreter.

These are sometimes also called as primitive data types.

Examples: Integers, Float, Complex Numbers, List, Tuple, Range, Strings, etc.

2. User defined Data Types: User defined data types are those data types which are created or derived with the help of built-in data types.

These are sometimes also called as Non-primitive data types.

Examples: Linked lists, Stacks, Queues, Trees, Graphs, etc.

You will learn about User defined data types in further articles.

Right now, our main focus is to understand all the Built-in data types in python.

So, Are you Ready?

Let’s begin!

Based on the size of memeory required by the data items, Built-in data types is classified into the following:

  • Numeric Types
  • Sequence Types
  • Set Types
  • Mapping Types
  • Boolean Types
Data types in python

Numeric Types:

What are numbers?

In plain English:

A number is an arithmetical value, which can be expressed or represent by a symbol (character), figure, or a word.

And,

Basically, It represents a particular quantity (amount) used to count and calculate something.

Or,

In other words:

Numbers are the type of data which consists numeric values, or we can say it is a type of data that represent numeric values.

Python has three built-in numeric data types:

1. Integers

2. Float

3. Complex Numbers

1. Integers:

An Integer is a positive and negative whole number including zero, with no decimal or fractional part.

In python, Integers can be of any length, there is no limit to how long an integer value can be.

It’s just depends upon the available size (amount) of memory your system has.

And, Most importantly, You can use an integer value as long as you need it to be at your particular situation.

Examples of Integers are:

Positive Integers: 1, 2, 3, 4, 5, 6, 7, 8, 9...

Negative Integers: -1, -2, -3, -4, -5, -6, -7, -8, -9...

Zero: 0 (Neither negative nor positive).

So,

In general, Integers are the set of: {-∞,... -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, ... +∞}

Integers are represented by int class.

You can use the type() built-in function to check or to get the type of a value or variable in python.

Example:

x = 10
type(x)

Output:

<class 'int'>    # This indicates that the variable x is of 'int' data type.


2. Float:

In mathematics, We have Real numbers.

And, Just like that, In python we have Float.

Float are also called as Floating-Point numbers.

There is only one difference between Real and Float numbers.

And,

The difference is: Real numbers may or may not contains decimal points, but Float or Floating-point numbers always contains decimal points.

So,

We can say:

Numbers with decimal points are called Float or Floating-Point numbers.

Or,

In other words, numbers which contains decimal points are called float or floating-point numbers.

Floating-point numbers are represented by float class.

Examples of Floating-point numbers:

3.14, 2.0, 6.022, 9.1 , 0.5 etc…

a = 3.14
type(a)

Output:

<class 'float'>


3. Complex Numbers:

A number which can be represented in the form of a+bj is called a complex number.

Where, a is called the real part and b is called the imaginary part.

And,

j is called the imaginary unit, and it’s simply the square root of -1 (i.e., √−1).

📝 Note: a and b both are real numbers.

So,

A complex number is basically a combination of real part and imaginary part.

Means: complex number = (real part) + (imaginary part)j.

A real number a can be considered as a complex number.

Because, We can write it as (a + 0j), whose imaginary part is 0.

A purely imaginary number bj is a complex number 0 + bj, whose real part is zero.

So, it is common to write a for a + 0j and bj for 0 + bj.

Examples of complex numbers:

5 + 8j, 7, 9j etc…

c = 3 + 7j
type(c)

Output:

<class 'complex'>


Sequence Types:

Python provides three basic sequence types:

1. Lists

2. Tuples

3. Ranges

Additional sequence type for processing of textual data (i.e., Strings) are described in a separate section.

1. Lists:

List is an ordered collection of data items.

Here, ordered collection simply means that, the data items (values) in a list have a definite order and are arranged in such a way that they form or follows a sequence (succession).

In simple words: Each item is concatenated (added) to a list one after the other, in the order in which they are inserted to the list.

📝 Note: In computers Data items are also called as values or elements.

The data items that you can store in a list may be of same type or different type. Means, all the data items in a list need not necessarily of the same type.

Lists are mutable sequences. Means, you can add, delete or change the values or the position of any data item of a list after it has been created.

You can also interchange the value or the position of any data item of a list after it is created.

And, by default, If you add new items to a list, the new items will automatically be placed at the end of the list.

List also allow duplicate values.

How you can create a list ?

You can create a list simply by placing a sequence of values inside square brackets ([ ]), where each value is separated by “comma” (,).

Examples:

nums = [23, 14, 45, 36, 7]   # Here, All the values are of same data type (i.e., integers)
print(nums)


names = ["Aryan", "Tom", "zeeshan"]
print(names)



# Here, All the values are not of same type. 
# First one is a integer, 
# second one is a string and at last the third one is of float type.

values = [5, 'python', 3.8]  
print(values)


# list also allow duplicate values. 
# Here, 2 is repeating two times 
# and 3 is repeating three times.

lst = [1, 2, 2, 3, 3, 3]   
print(lst)

Output:

[23, 14, 45, 36, 7]

['Aryan', 'Tom', 'zeeshan']

[5, 'python', 3.8]

[1, 2, 2, 3, 3, 3]

You can also insert a list inside a list.

Example:

rank = [[3, 5, 1, 4, 38], ['java', 'c', 'python', 'c++', 'ruby']]
print(rank)

Output:

[[3, 5, 1, 4, 38], ['java', 'c', 'python', 'c++', 'ruby']]

In python, you can create an empty list by the two following ways:

1. Using the list() Constructor

You just have to assign the list() constructor to a variable without passing any argument inside the parentheses of list() constructor.

Example:

# creating an empty list
# using list() constructor

x = list()

print("Empty list: ", x)
type(x)

Output:

Empty list: [ ]   # An empty list is created (no element inside the square brackets)
<class 'list'>    # x is of list type

2. Using square brackets

You can also create an empty list just by assigning a square brackets [ ] to a variable. Where you don’t have to pass anything inside the square brackets.

Example:

# Creating an empty List
# using square brackets

empty_list = []

print("Empty List: ", empty_list)
type(empty_list)

Output:

Empty list:  []
<class 'list'>

How you can access (fetch) elements from a list ?

Accessing an element from a list is as simple as placing the index value of that element inside a square brackets [ ] which you want to access.

📝 Note: The first data item (element) has index [0], the second element has index [1] and so on…

It means, indexing starts from 0 in python and goes till the total number of elements minus one.

If total number of elements in a list is let’s say n, then the index value will go till n-1.

The index value that you place inside the square brackets must be integers.

You can’t use floating point numbers or any other data type inside the square brackets as an index value.

Examples:

# accessing elements from a list

nums = [23, 14, 45, 36, 7] 
print(nums[0])
print(nums[4])


# Nested lists are accessed using nested indexing

rank = [[3, 5, 1, 4, 38], ['java', 'c', 'python', 'c++', 'ruby']]


print(rank[1][0])
print(rank[0][1])

Output:

23
7
java
5

You can also access elements from a list using negative indexes. Negative indexing simply means that, starting from the end of the list.

The index value -1 gives the last element, -2 gives the second last element of a list and so on…

So,

In short: The last element of the list is the first element in the negative indexing which is -1.

Examples:

# Accessing elements from a list using negative indexes

values = [5, 'python', 3.8]

print(values[-1])
print(values[-2])
print(values[-3])

Output:

3.8
python
5


2. Tuples:

Tuple is almost similar as a list, but there are some differences.

And, The differences are:

1. Tuples are immutable.

Immutable simply means that, The data items (values) or the position of any data item cannot be changed or modified after it is created.

It does not support reassigning of value at any specified position.

2. Instead of using square brackets as we were doing in creating a list, you can create a tuple by using a parentheses (round brackets).

So,

Basically, Tuples are ordered collection of immutable data items.

Since we don’t change the value in tuple so, iteration in tuple is faster than in lists.

That’s why we can use tuple if we want to enhance the speed of execution of a program.

How you can create a tuple ?

You can create a tuple simply by placing a sequence of values inside parentheses (), where each value is separated by “comma” (,).

Examples:

tup = (98, 39, 12, 46, 103)
print(tup)

tup[0] = 23  # gives an error

tup_1 = ("Tuple", 5+10j, 2, 3.19)
print(tup_1)

Output:

(98, 39, 12, 46, 103)

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    tup[0] = 39
TypeError: 'tuple' object does not support item assignment

('Tuple', 5+10j, 2, 3.19)

You can create an empty tuple just by assigning a parentheses () to a variable. Keep in mind, Nothing should be inside the parentheses.

Example:

empty_tuple = ()
print(empty_tuple)

Output:

()  # an empty tuple is created

How you can access elements from a tuple ?

You can access elements from a tuple just by placing the index value of that element inside a square brackets [ ] which you want to access.

It means, Accessing an element from a tuple is similar as accessing an element from a list.

Example:

tup = (1, 2.0, "data", 5+10j)

print(tup[2])
data

print(tup[3])
(5+10j)

print(tup[0])
1


print(tup[-1])    # Accessing element from a tuple using negative indexing
(5+10j)

tup[-2]
data

tup[-4]
1

tup[-3]
2.0

# Nested tuples are accessed using nested indexing.

new_tuple = (1, 2.0, "data", 5+10j, ('pyhon', 'java', 'c'))  # tuple inside a tuple

print(new_tuple[4][2])  
c

print(new_tuple[4][0])
pyhon

print(new_tuple[4][1])
java


3. Ranges:

In python, range is basically a built-in function that returns an immutable sequence of numbers.

Or,

It will be better to say that, The range function generates an immutable sequence of numbers.

And, by default, the sequence of numbers starts from 0 (zero), and increments by 1, and stops before a specified number (the number that you passed as an argument inside the parentheses of range() function).

It is commonly used in for loops to iterate (repeat) the loop a specific number of times.

It means, If you use for loop with range() function by passing some iterables (arguments) to it, it allows you to perform an action (task) for a specific number of times.

📝 Note:

The arguments to the range function must be integers. You can’t use floating point numbers or any other data type inside the range function.

There are three ways you can define or call range() function:

range(stop) takes only one argument.

range(start, stop) takes two arguments.

range(start, stop, step) takes three arguments.

Parameter (argument)Description (meaning)
startIt is optional, An integer number which specifies the starting point of range(). By default it is 0.
stopAlways required, An integer number which specifies the ending point ( the upper limit) of range(). But, the upper value is not included.
stepOptional, An integer number which specifies the increment or decrement between two consecutive numbers. By default it is 1.

So,

From the above table, you can conclude that,

The number of arguments that you passed to the range function determines the following:

1. From where the sequence of numbers will begin.

2. Where the sequence will end.

3. How big the difference will be between two consecutive numbers.

For a positive step, the contents of a range r are determined by the formula r[ i ] = start + step * i, where i >= 0 and r[ i ] < stop.

For a negative step, the contents of a range r are determined by the formula r[ i ] = start + step * i, but the limitations are i >= 0 and r[ i ] > stop.

Examples:

range(stop) takes only one argument.

# empty range
print(list(range(0)))
[ ]

# using range(stop)
nums = range(5)
print(list(nums))
[0, 1, 2, 3, 4]

for i in range(11):
    print(i, end =" ")

0 1 2 3 4 5 6 7 8 9 10

range(start, stop) takes two arguments.

lst = range(1, 10)
print(list(lst)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

for a in range(10, 20):
    print(a, end =" ")

10 11 12 13 14 15 16 17 18 19 

range(start, stop, step) takes three arguments.

# incremented by 2
for i in range(3, 30, 2):
    print(i, end =" ")

3 5 7 9 11 13 15 17 19 21 23 25 27 29

# decremented by 3 or incremented by -3
for i in range(30, 1, -3):
    print(i, end =" ")

30 27 24 21 18 15 12 9 6 3 

Text Sequence Type:

String

String:

In python, A string is a sequence of characters, the characters might be alphabets, numbers and special symbols.

All the characters in a string do not need to be of same type. Means, you can use alphabets, numbers and special symbols in the same string.

In python, Strings are surrounded (enclosed) by either a single quotes, double quotes or triple quotes.

‘Python’ always treats a string a single data even though it contains whitespaces.

And, If a white space comes anywhere inside a quotation mark, python treats it as a character of a string.

Even only a single white space enclosed inside a quotation mark is considered to be a string.

The only requirement to make a string is, the text or the sequence of characters must be enclosed inside the quotation marks.

And, Strings can be of any length, there is no limit to how long a string can be.

In python, A single character is also considered a string with a length of 1.

📝 Note:

1. Strings in python are immutable sequences.

2. Triple quotes are usually used for creating a string that spans multiple lines.

How you can create a string ?

You can create a string in python just by placing a sequence of characters inside either a single quotes, double quotes or even triple quotes. 

And, To print or to display a string into your computer screen you can use print() function.

Examples:

name = 'python'  #creating a string using single quotes.

print(name)
python


name = "python"  #creating a string using double quotes.

print(name)
python


name = '''python'''  #creating a string using three single quotes.

# or

name = """python"""  #creating a string using three double quotes.

print(name)
python


mail_id = "[email protected]"  # alphabets, numbers and special symbols in the same string

print(mail_id)
[email protected]

# creating a multiline string using three double quotes.

text1 = """This is an example
of multiline string 
in python."""
print(tex1)


# creating a multiline string using three single quotes.

text2 = '''This is an example
of multiline string 
in python.'''
print(text2)

Output:

This is an example
of multiline string 
in python.


This is an example
of multiline string 
in python.

How you can access elements (characters) of a string ?

You can access elements of a string just by placing the position of that character inside a square brackets [ ] which you want to access.

📝 Note:

The position of the first character of a string is always zero.

Example:

a = "Hello, world"
a[0]    # accessing the first element of "Hello, world"
'H'

# or 
print(a[0])
H

a[6]
' '             # a white space

print(a[5])
 ,           # comma

Set Types:

In python, There are two built-in set types:

1. Set

2. Frozen Set

1. Set:

A Set is an unordered collection of unique elements.

Since sets have unique elements, so if you insert a single element more than one time in a set, then it does not print or display duplicate elements.

And,

As I have already mentioned above, sets are unordered collection of elements. Which means that, the data items in a set do not have a definite order. Elements are arranged in a random order and never form or follows a sequence (succession).

Sets are unordered, so you cannot be sure in which order the items will appear.

Therefore, no any specific position or index value are specified for any given elements.

So,

If you want to fetch any value of a set by specifying the index value, then it will throw an error.

Set do not record element position or order of insertion. so, sets do not support indexing, slicing, or other sequence-like behaviors.

The data items (values) that you can store in a set can be of any data type.

A single set can contain same data type or different type. Means, All the data items in a set need not necessarily of the same type.

But,

There is one restriction, Each and every element of a set must be immutable.

If you insert a mutable type of data item to a set, then it will throw an error.

However, a set itself is mutable.

How you can create a set ?

You can create a set simply by placing a series of elements inside curly braces ({ }), separated by comma.

Examples:

s = {3, 2, 5, 7, 1}  # all the items are of integer type
print(s)


new_set = {0, 2.5, 3+5j, 'set', (2, 4, 6)}   # all the items are not of same data type
printt(new_set)

Output:

{1, 2, 3, 5, 7}    # It is looking like a sorted sequence, but it is not sorted. Because, set never follows a sequence.


{0, 2.5, (3+5j), 'set', (2, 4, 6)}

Sets can also be created by using the built-in set() function.

In this case, you have to pass an iterable as an argument inside the parentheses of set() function.

The iterable can be a list, tuple or a string. Because, these all are iterables that generates a list of objects (itmes) to be included in the set. 

Examples:

a = set(['pyhton', 'java', 'c', 'c++', 'javaScript'])   # list as an iterable
print(a)


b = set((3, 6, 9, 12, 15))   #tuple as an iterable
print(b)


state = set('karnataka')    # string as an iterable
print(state)

Output:

{'pyhton', 'c', 'javaScript', 'c++', 'java'}

{3, 6, 9, 12, 15}

{'a', 'r', 'n', 't', 'k'}

As you can see in the outputs of the above examples, set do not maintain the original order of elements, as specified at the time of creating or defining a set.

In addition, duplicate values are only represented in the set once, as with the string the letter 'k' and 'a' in the last example.

An “empty set” can be created just by using set() function without passing any argument inside the parentheses.

Example:

empty_set = set()

print(empty_set)

type(empty_set)

Output:

set()    # an empty set is created

<class 'set'>    # type of the variable (empty_set) is set

How you can access elements from a set ?

As we have already seen, sets are unordered, Therefore, no any specific position or index value are specified for any given elements.

So,

You cannot be sure in which order the items will appear.

And,

That’s why, set items cannot be accessed by referring to an index value.

However, you can print (display) the items of a set by using a for loop.

Or,

You can check if a specific value is present in a set or not, by using the Membership operator (in or not in).

Examples:

s = {2, 4, 6, 8}

# printing elements using 
# for loop
for i in s:
    print(i, end=" ")

# checking the element is present in a set or not
# using in keyword

print(4 in s)

Output:

8 2 4 6   # elements of set 's'

True    # this shows that, 4 is present in the set 's'

2. Frozen Set:

In python, frozenset() is a built-in function which takes an iterable (argument) as input and makes them (the argument that you pass inside the parentheses of frozenset() function) immutable.

The above statement simply means that, If the passed iterable object inside the parentheses of frozenset() function is either of mutable or immutable type, then the frozenset() function returns the same iterable object but the type will converted into immutable type.

Here, an iterable objects can be list, tuple, sets etc.

Frozenset is almost similar as a set in all respect. The only difference is: Frozenset is immutable. Whereas, sets are mutable.

How you can create a FrozenSet ?

You can create a frozenset using the frozenset() function.

The syntax of frozenset() function is:

Syntax : frozenset(iterable_object_name)

Example:

# list of even numbers
lst = [2, 4, 6, 8, 10]

# converting list to frozenset
flist = frozenset(lst)

print("frozenset is : ", flist)

Output:

frozenset is:  frozenset({2, 4, 6, 8, 10})

If you do not pass any argument inside the parentheses of frozenset() function, it returns an empty frozenset.

Example:

print("The empty frozen set is: ", frozenset())

Output:

The empty frozen set is:  frozenset()

Mapping Types:

In python, There is only one mapping type, the dictionary.

And, most of the time mapping is also called as dictionary.

So, you can use these two words (i.e., dictionary and mapping) interchangeably.

Dictionary is almost similar as a set, but there are few differences,

And, the differences are:

1. Unlike set or any other data types that carry only single value as a data item (element), Each data item of a dictionary has a key-value pair.

2. In dictionary, Keys are immutable and values can be of any type (mutable and immutable both), but in set all the values are mutable.

3. In dictionary, all the keys must be unique whereas the values can repeat, but in set all the values must be unique.

So, you can say:

A Dictionary is an unordered collection of key-value pairs.

Or,

It is better to say that a dictionary is a set of unordered collection of key-value pairs.

If you talk about only keys and values of a dictionary separately, then keys are immutable and values are mutable and immutable both.

Whereas, If you talk about Dictionaries, a dictionary itself is mutable.

📝 Notes:

Keys of a dictionary must be immutable type like numbers, tuples or strings. And, The best part is: we generally use numbers or strings as a key.

Values can be of any data type.

Dictionary does not allow duplicate keys. So, you can’t use a same key for two different values.

Values can be duplicated.

Keys of a dictionary are case sensitive. This means, Same name but different cases of key will be treated distinctly.

Example:

student, Student and STUDENT are not same. Because the word student is completely in lowercase, the first character of Student is in uppercase and the last STUDENT is completely in uppercase.

How you can create a dictionary ?

You can create a dictionary simply by placing a sequence of key-value pairs inside curly braces { }, where each key-value pair is separated by “comma” (,) from its next key-value pair.

A colon ( : ) separates each key from its associated (corresponding) value.

Following example shows the general form of a dictionary:

dictionay_name = {key1:value1, key2:value2, key3:value3}    

Examples:

student_information = {1: 'start', 'name': 'Rohan', 'age': 20, 'branch': 'cse', 'roll_number': 13, 'friends': {'Farman', 'Mohit', 'Basant'}, 'favourite_subjects': ['Mathematics', 'Computer science', 'Electronics']}

print(student_information)
{1: 'start', 'name': 'Rohan', 'age': 20, 'branch': 'cse', 'roll_number': 13, 'friends': {'Basant', 'Farman', 'Mohit'}, 'favourite_subjects': ['Mathematics', 'Computer science', 'Electronics']}

# or

student_information = {1.0: 'start', 'name': 'Rohan', 'age': 20, 'branch': 'cse', 'roll_number': 13, 'friends': {'Farman', 'Mohit', 'Basant'}, 'favourite_subjects': ['Mathematics', 'Computer science', 'Electronics']}


print(student_information)
student_information = {1.0: 'start', 'name': 'Rohan', 'age': 20, 'branch': 'cse', 'roll_number': 13, 'friends': {'Farman', 'Mohit', 'Basant'}, 'favourite_subjects': ['Mathematics', 'Computer science', 'Electronics']}

In the above examples, you can see that the keys are strings or numbers (int or float). The values, on the other hand, are many varied data types.

You can also create a dictionary using the built-in dict() function.

And, an empty dictionary can be created by just placing a curly braces { } without passing any argument inside the curly braces.

Or, by using dict() function without passing any argument inside the parentheses of dict() function.

Example:

# creating an empty dictionary

{}   # using curly braces

dict()    #using dict() function

Output:

{}

{}

How you can access elements from a dictionary ?

Unlike lists, tuples or strings, where we place index values (i.e., positions) of elements inside the square brackets [ ] to access data items (values), a dictionary uses keys to access values and not the integer indexes.

You can access elements from a dictionary by placing the key of that value inside a square brackets [ ] which you want to access.

So,

You must know the key to retrieve (access) the associated value.

Examples:

d = {'A': 'Apple', 'B': 'Boy', 'C': 'Cat', 'D': 'Dog'}

d['A']         # using key inside the square brackets to access element

d['D']

Output:

'Apple'

'Dog'

The get() method is also used to access the elements of a dictionary. It returns the value of the item with the specified key.

Syntax to use get() method:

dictionary_name.get(key)

Examples:

d = {'A': 'Apple', 'B': 'Boy', 'C': 'Cat', 'D': 'Dog'}

# using get() method to access the elements.

d.get('B')    # using get() method to access the element.

d.get('C')

Output:

'Boy'

'Cat'

📝 Notes:

If you place a key inside the square brackets which has not any associated value, then dictionary throws a KeyError.

In other words: If you are looking up a value which is not in the dictionary, then dictionary throws a KeyError.

Whereas, If you use get() method, then the dictionary returns the value associated with the specified key (the key which is inside the get method) or None if the key is not present in the dictionary.


Boolean Types:

Boolean type is one of the most important and powerful built-in data types in python.

You: How Booleans are most important and powerful?

Me: If you look back, a lot of your code is all about making decisions and then taking the appropriate action. Right?

And, here Booleans comes into picture.

Booleans are used to obtain the truth value of an expression or a condition where you have to compare or to decide whether a given condition is either “True” or “False”.

And, these “True” and “False” are called Boolean values.

Whenever you type an expression at the python prompt to evaluate the truth value of the expression, then the evaluation of that expression gives you the output in the form of Booleans (i.e., “True” and “False”).

Or,

When you pass a parameter (argument) in the form of an expression to the bool function [bool()] it returns either “True” or “False” as a result.

It means, you can find the truth value of an expression either by using the bool() function or just only by typing the expression at the python prompt (without using the bool() function).

So, there is no need to always use the bool function to obtain the truth value of an expression or a condition.

Hence, from the above discussion we can conclude that, Boolean type is a type which has only two possible values, “True” and “False”.

Booleans are denoted by class bool.

Examples:

x = True
type(x) 
<class 'bool'>   # This indicates that the variable x is a boolean data type.

y = False
type(y)
<class 'bool'>

a = 2
b = 5

a >= b
False

a <= b
True

📝 Notes:

True and False are not ordinary words. These are keywords.

First letter of True (i.e., “T”) and first letter of False (i.e., “F”) must be in upper case. If you use lower case “t” or lower case “f”, then python will return an error.

It is valid to assign a Boolean value to variables, but it’s not valid to assign a value to either True or False.

Because, True and False are keywords.

And,

As we already know:

Keywords are generally used for defining the syntax and structure of python language.

The meaning of python keywords has already been described to the python interpreter.

These meaning cannot be changed.

Thus, Keywords cannot be used as a variable name, function name, class name or any other identifier.

Because, that would try to change the existing meaning of the keyword, Which is not allowed.

That’s why, you can’t assign a value to either True or False.

Example:

True = 1
SyntaxError: cannot assign to True

False = 0
SyntaxError: cannot assign to False

Booleans as Numbers:

Most of the time many programmers put Booleans under the category of numeric data type and they considered Booleans as a numeric type.

The reason behind is that, If you pass “True” and “False” as an argument to the int, float or complex function. you’ll get 1 and 0 respectively as an output.

Just like this:

int(True)
1
int(False)
0

float(True)
1.0
float(False)
0.0

complex(True)
(1+0j)
complex(False)
0j

And, we can also use bool() function to convert Integers, float and complex numbers into Boolean type.

An integer, float or complex number set to zero returns False.

And, An integer, float or complex number set to any other numbers, positive or negative returns True.

Examples:

bool(0)
False

bool(1)
True

bool(-974056)
True

So,

Basically, True is equal to 1 and False is equal to 0.


Why do we need data types? (Why data types is so important)

When you work on a project, It’s very important to understand whatever data you are working with, so that you can process that data in that format.

Because, If you don’t process the data in that particular format, you might face errors or bugs.

And, That’s why we need data types in any programming languages.


Conclusion:

In this article, you learned what are data types in Python, you also became familiar with the different types of data types, How to create them, and How to access the elements from each data types with their syntaxes and lots of examples.

So,

I really hope that you liked my article and got a lot of value from it.

Now, It’s your turn!

If you have any question, feel free to ask in the comment section below right now.


Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *