Python Data types
This tutorial deals with the basic python data types of Python programming language. Before you start reading this tutorial you need to have a basic understanding of python programming language. If you have read the basic section then proceed otherwise here take a look at the basics of python programming language.
Table Of Contents of Python Data Types
What is Data type?
A Python data type is simply an attribute of the data which tells the interpreter of the programming language that a programmer wants to use this data in this type of format. Some common datatypes of a programming language are Integer, Float, Boolean, String.
Python Datatypes consist of
- Numbers
- String
- List
- Tuple
- Set
- Dictionary
Numbers
Numbers data type consist of three sub-data types of Python Programming language.
- Integer
- Float
- Complex
All these Number Data types consist of a class built into python programming language. Known as int class
,float class
,complex class
.
Integer(int)
With python 3 in use, the length of an integer variable is not a problem, the only problem that can arise is whether your system’s memory can handle that big of an integer or not.
To define a integer variable in python you just need to assign it to a variable without using any decimal values otherwise, it would convert into float datatype
.
Number = 5 Sum = 5+3 print(Number) print(Sum) print(type(Sum))
type()
is built in method in python programming language which checks the class this variable belongs to!!
So by running the compiler, we get the output on the console as
5 8 <class 'int'>
Float(float) data type
The difference between an integer data type and a float data type is of decimal values.
For example
Number = 5 Number1 = 5.0 print(type(Number)) print(type(Number1))
Well, what do you think? Both the numbers seems the same right? Let’s take a look at the output console
<class 'int'> <class 'float'>
Now you can see that both the numbers belong to the different datatypes class of python programming language under python data types. Just because of a decimal.
You can convert int variable to a float variable and a float variable to an int.
>>>b = 5 >>>type(b) <class 'int'> >>>b = float(b) >>>type(b) <class 'float'>
Converting of a float variable to an int variable is same but while converting you will lose the decimal portion of the variable. Hence Do it only when the decimal values are not that of much importance for your code otherwise you will get a different output as it might affect your code.
Float datatypes of python data type can have any length of numbers before as that of an integer but after the decimal, it is accurate to 16 digits.
>>>b=0.12345678956784568767687678678687678678 >>>b 0.12345678956784568
See that the output got truncated to 16 digits after the decimal point.
Complex Data type(complex)
You write these data types in the form of x+yj
where x
is the real part of the number and y
is the imaginary part of the number.
>>>b = 5+6j >>>c (5+6j) >>>print(type(c)) <class ‘complex'>
String Data type
It is a sequence of characters enclosed within single quotes(‘ Hi I’m a string’) or within double quotes(“Hi I’m a string too”).
By using triple single quotes or double quotes, we can have a multiline string.
”"" Hi I’m a multiline string.
And it's awesome”””
String variables same as Number Datat ypes can have any length of strings, the only thing that would stop you from processing would be your system memory capacity. And a string can be empty too meaning that these quotes would not contain anything in between them.
>>>b = “Hi I’m a string” >>>b “Hi I’m a string too” >>>type(b) <class ‘string’> >>>c = ‘ ‘ >>>c ‘ ‘ >>>type(c) <class ‘string’>
However When you are using single quotes or double quotes to define a string and use the same type of quotes in the string itself then you would get an error which says <code>SyntaxError: invalid syntax</code>. Let’s see it in the code first before further explanation.
>>>print(‘hi I’m using single quotes inside the string itself.’) SyntaxError: invalid syntax
The reason for this is that the python receives the first quote as the beginning of the string, so it thinks that the next single quote will be the closing delimiter. The next single quote it encounters lies in the string itself. So python considers it as the ending of that string and is not able to read the next characters. Hence generates syntax error which means that there is something wrong with the syntax of the code.
There are many ways to bypass this. One is using double quotes as the string delimiter and single quotes inside the string and other are to use escape sequence which let the python to ignore that quote and move to the next character and runs until it finds the closing delimiter.
>>>print(“Hi I’m using single quote inside my string.”) “Hi, I’m using single quote inside my string.” >>>print(‘Hi I\’m using single quote inside my string.’) ‘Hi, I’m using single quote inside my string.’
Since String data types is a sequence of characters, you can think of it as an array of characters. We can perform List
operations on the string variables. You will learn about List
in the next section.
List
A list is the ordered collection of non-homogeneous data. Unlike arrays in C or C++ you can store string, float, int, complex datatypes values in a single list and operate on them in one place according to your need. List is used to implementing stack and queues in python using Collections.
Creating a list is very easy, You can create an empty list or list with certain values in it as per your requirement.
>>>b = [ ] >>>type(b) <class ‘list’> >>>b = [1, ‘abc’, 5.7] >>>print(b) [1, ‘abc’, 5.7] >>>type(b) <class ‘list’>
Operations to be performed on the list are very easy to work with when you’re dealing with python data type. You can increase the length of the list using append()
method or you can reduce the length using pop()
method and many more.
Operations that are performed on list
>>>b = [ ] >>>b.append(1) >>>b.append(2) >>>b.append(3) >>>b [1,2,3] >>>b.pop() 3
Here by using append method we inserted the values inside the list and by using pop() method we are removing the last element from the list.
Tuple
A tuple is a collection of non-homogeneous data in an ordered format which is basically the same for List
but it’s not same as List as its unmutable which means that once declare a value inside a tuple you cannot change it. Which is allowed in List
and due to this Tuple is faster than List in execution because of no dynamic changes.
Tuple is enclosed inside parenthesis () but the values inside Tuple are called using slicing operator [ ]
1 >>>tup[0] = 2 Traceback (most recent call last): File "<stdin>", in <module> t[0] = 2 TypeError: 'tuple' object does not support item assignment
Set
Set is a collection of uniques values in an unordered fashion enclosed within curly braces { }
. Since there is no ordering present in the set, the use of slicing operator is not present in the set.
Set consist of unique values which means that if you have two same values in a set then after execution it will remove the copy and maintains its uniqueness.
All the mathematical Set operations can be performed on these sets too such as union, intersection, addition, subtraction etc
>>>s = {1,2,3,4,5,5} >>>s {1,2,3,4,5} >>>type(s) <class ‘set’> >>>s = s+{6,7,8} >>>s {1,2,3,4,5,6,7,8} >>>s[1] Traceback (most recent call last): File "<string>", in runcode File "<interactive input>", in <module> TypeError: 'set' object does not support indexing
Dictionary{key:value}
Dictionary is a collection of unordered key: value pairs. Dictionaries in python are used to store a large amount of data which are in the form of a map. Each data is associated with a unique key which makes it’s easy to access the data in a dictionary. Due to this Key: Value format the optimization is the best among others.
You can think of python dictionary same as that of a normal dictionary book, Python dictionary is enclosed within curly braces { }.
# Creating an empty Dictionary D = {} print(D) # with Integer Keys D = {1: 'python', 2: 'For', 3: 'warriors'} print(D) # with Mixed keys D = {'Name': 'Python', 1: [6,7,8,9]} print(D) # with dict() method D= dict({1: 'Python', 2: 'is For', 3:'Warriors'}) print(D) # with each item as a Pair D = dict([(1, 'Python'), (2, ‘Warrior')]) print(D)