Python – Data Type

In this tutorial, you will learn about different data types you can use in Python.

Data types in Python

Each value in Python has a datatype. Because everything in Python programming is an object, data types are essentially classes, and variables are instances (objects) 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 are all examples of Python numbers. They are known as int, float, and complicated classes in Python.

The type() method can be used to identify which class a variable or value belongs to. The isinstance() function determines whether or not an object belongs to a particular class.

a = 5
print(a, "is of type", type(a))

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

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

Output

5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True

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

Up to 15 decimal digits, a floating-point number is accurate. Decimal points separate integers and floating points. 1.0 is a floating-point number, while 1 is an integer.

Complex numbers are written as x + yj, where x represents the real part and y represents the imaginary part. Here are a few illustrations.

>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)

Notice that the float variable b got truncated.



2) List

Lists are ordered collections of data, similar to arrays, which are declared in other languages. It’s particularly adaptable because list items don’t have to be of the same type. 

Creating List

Lists in Python can be created by just placing the sequence inside the square brackets[].

Consider the following example, in which we will utilize negative indexing to access the list’s elements.

  1. list = [1,2,3,4,5]  
  2. print(list[-1])  
  3. print(list[-3:])  
  4. print(list[:-1])  
  5. print(list[-3:-1])  

Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

Python Tuple

A tuple, like a list, is an ordered series of elements. Tuples vary solely in that they are immutable. Tuples can’t be changed once they’ve been generated.

Tuples are used to write-protect data and, because they do not alter dynamically, are usually faster than lists.

It is defined within parentheses () where items are separated by commas.

t = (5,'program', 1+3j)

We can use the slicing operator [] to extract items but we cannot change its value.

t = (5,'program', 1+3j)

# t[1] = 'program'
print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])

# Generates error
# Tuples are immutable
t[0] = 10

Output

t[1] =  program
t[0:3] =  (5, 'program', (1+3j))
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    t[0] = 10
TypeError: 'tuple' object does not support item assignment

Python Strings

The term “string” refers to a collection of Unicode characters. To represent strings, we can use single or double quotations. Triple quotes, “‘ or “””, can be used to signify multi-line strings.

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

A set is an unsorted collection of one-of-a-kind goods. Values separated by commas inside braces define a set. The items in a set are not ordered in any particular sequence.

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]
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing

Python Dictionary

Dictionary is an unordered collection of key-value pairs.

When we have a large amount of data, we usually use it. The retrieval of data is enhanced in dictionaries. To get the value, we need to know the key.

In Python, dictionaries are defined inside braces, with each item being a key:value pair. Any type of key and value can be used.

>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>

We use key to retrieve the respective value. But not the other way around.

d = {1:'value','key':2}
print(type(d))

print("d[1] = ", d[1])

print("d['key'] = ", d['key'])

# Generates error
print("d[2] = ", d[2])

Output

<class 'dict'>
d[1] =  value
d['key'] =  2
Traceback (most recent call last):
  File "<string>", line 9, in <module>
KeyError: 2

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')
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'

We can even convert one sequence to another.

>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

To convert to dictionary, each element must be a pair:

>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}

Leave a Comment

Your email address will not be published.