Python Datatypes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Data types in Python

Every value in Python has a datatype. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.

There are various data types in Python. Some of the important types are listed below.

Python Numbers
Integers, floating point numbers and complex numbers fall under Python numbers category.
They are defined as int, float and complex classes in Python.

We can use the type() function to know which class a variable or a value belongs to. Similarly,
the isinstance() function is used to check if an object belongs to a particular class.
Example
a=5
print(a, "is of type", type(a))

Output
5 is of type <class 'int'>

Example
a = 2.0
print(a, "is of type", type(a))

Output
2.0 is of type <class 'float'>

Example
a = 1+2i
print(a, "is complex number?", isinstance(1+2j,complex))

Output
(1+2i) is complex number? True

Integers can be of any length, it is only limited by the memory available.

A floating-point number is accurate up to 15 decimal places. Integer and floating points are
separated by decimal points. 1 is an integer, 1.0 is a floating-point number.

Complex numbers are written in the form, x + yi, where x is the real part and y is the
imaginary part. Here are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789

>>> b = 0.1234567890123456789
>>> b
0.12345678901234568

>>> c = 1+2i
>>> c
(1+2i)
Notice that the float variable b got truncated.

Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible. All the items in a list do not need to be of the same type.

Declaring a list is pretty straight forward. Items separated by commas are enclosed within
brackets [ ].

list = [1, 2.2, 'python']


We can use the slicing operator [ ] to extract an item or a range of items from a list. The
index starts from 0 in Python.
a = [5,10,15,20,25,30,35,40]

# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15] last index


print("a[0:3] = ", a[0:3]) start index

# a[5:] = [30, 35, 40]


print("a[5:] = ", a[5:])

Output
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]

Lists are mutable, meaning, the value of elements of a list can be altered.
a = [1, 2, 3]
a[2] = 4
print(a)

Output
[1, 2, 4]

Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)

Output
This is a string
A multiline
string

Just like a list and tuple, the slicing operator [ ] can be used with strings. Strings, however,
are immutable.
s = 'Hello world!'

# s[4] = 'o'
print("s[4] = ", s[4])

# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])

# Generates error
# Strings are immutable in Python
s[5] ='d'

Output
s[4] = o
s[6:11] = world

Traceback (most recent call last):


File "<string>", line 11, in <module>
TypeError: 'str' object does not support item assignment

Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.
a = {5,2,3,1,4}

# printing set variable


print("a = ", a)

# data type of variable a


print(type(a))

Output
a = {1, 2, 3, 4, 5}
<class 'set'>
We can perform set operations like union, intersection on two sets. Sets have unique
values. They eliminate duplicates.
a = {1,2,2,3,3,3}
print(a)

Output
{1, 2, 3}

Since, set are unordered collection, indexing has no meaning. Hence, the slicing
operator [] does not work.
>>> a = {1,2,3}
>>> a[1]

Python tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas we can change the elements of a list.

A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional.

A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

In the above example, we have created different types of tuples and stored different data
items inside them.

As mentioned earlier, we can also create tuples without using parentheses:

my_tuple = 1, 2, 3
my_tuple = 1, "Hello", 3.4

Create a Python Tuple with one Element


In Python, creating a tuple with one element is a bit tricky. Having one element within
parentheses is not enough.

We will need a trailing comma to indicate that it is a tuple,

var1 = ("Hello") # string


var2 = ("Hello",) # tuple

We can use the type() function to know which class a variable or a value belongs to.

var1 = ("hello")
print(type(var1)) # <class 'str'>

# Creating a tuple having one element


var2 = ("hello",)
print(type(var2)) # <class 'tuple'>

# Parentheses is optional
var3 = "hello",
print(type(var3)) # <class 'tuple'>
Run Code
Here,

("hello") is a string so type() returns str as class of var1 i.e. <class 'str'>
("hello",) and "hello", both are tuples so type() returns tuple as class of var1 i.e. <class
'tuple'>

Advantages of Tuple over List in Python


Since tuples are quite similar to lists, both of them are used in similar situations.

However, there are certain advantages of implementing a tuple over a list:


• We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than with a list. So there
is a slight performance boost.
• Tuples that contain immutable elements can be used as a key for a dictionary. With
lists, this is not possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.

Conversion between data types


We can convert between different data types by using different type conversion functions
like int(), float(), str(), etc.
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
Conversion to and from string must contain compatible values.
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')

You might also like