Skip to main content

Python Datatypes

Datatypes in Python

In Python, every value has a datatype and every type is an object.

So:

  • datatypes are actually classes
  • variables are instance (object) of these classes

The main types in python are briefly explained below. For a more in-depth look at the individual typology pages (linked in each section).

Python Numbers

Integer, floating-point and complex numbers are numeric datatypes. Respectively they are defined as int, float and complex classes.

  • Integer numbers 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. For example, 1 is an integer, 1.0 is a floating-point number.
  • Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.
integer_var = 1234567890123456789
float_var = 0.1234567890123456789
complex_var = 1+2j
print(integer_var) # print 1234567890123456789
print(float_var) # print 0.123456789012345678
print(complex_var) # print (1+2j)
note

Note that the variable float_var has been truncated because the accuracy is up to 15 decimal places.

note

See Python numbers chapter for more details.

Python List

Python List is an ordered sequence of elements.

  • Lists are mutable, meaning that the value of elements in a list can be changed.
  • It is not necessary that all elements in a list be of the same type.

The slicing operator [ ] is used to operate on lists: to declare a list and to extract an element or a range of elements from a list.

my_list = [1, 2.3, 'a string']

# my_list[1] = 2.3
print("my_list[1] = ", my_list[1])

# my_list[0:1] = [1, 2.3]
print("my_list[0:1] = ", my_list[0:1])

# my_list[1:] = [2.3, 'a string']
print("my_list[1:] = ", my_list[1:])

my_list[0] = 10 # change value at index = 0
print(my_list) # [10, 2.3, 'a string']
note

In Python, the list index starts from 0.

note

See Python list chapter for more details.

Python Tuple

Python Tuple is an ordered sequence of immutable items.

Tuples are similar to lists, but once created they can't be modified.

note

Tuples are used to protect data in writing and are usually faster than lists because they can't change dynamically.

A tuple is defined by listing the elements in round brackets ( ), separated by commas:

my_tuple = (1,'a string', 1+2j)

The slicing operator [] can only be used to extract elements.

my_tuple = (1,'a string', 1+2j)

# my_tuple[1] = 'a string'
print("my_tuple[1] = ", my_tuple[1])

# my_tuple[0:3] = (1, 'a string', (1+2j))
print("my_tuple[0:3] = ", my_tuple[0:3])

# Generates error because tuples are immutable
my_tuple [0] = 100

Output:

my_tuple[1] = a string
my_tuple[0:3] = (1, 'a string', (1+2j))
Traceback (most recent call last):
File "test.py", line 10, in <module>
my_tuple[0] = 100
TypeError: 'tuple' object does not support item assignment
note

See Python tuple chapter for more details.

Python Strings

Python String is sequence of Unicode characters.

  • Single quotes or double quotes can be used to represent strings.
  • Multi-line strings can be indicated with triple quotes, ''' or """.
  • Strings are immutable
s = "This is a string"
print(s)
s = '''This is
a multiline
string'''
print(s)

Output

This is a string
This is
a multiline
string

As with lists and tuples, the slicing operator [ ] can be used with strings.

s = 'Hello world!'

# s[1] = 'e'
print("s[1] = ", s[1])

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

# Generates error because strings are immutable
s[5] ='d'

Output

s[1] = e
s[6:11] = world
Traceback (most recent call last):
File "<string>", line 10, in <module>
TypeError: 'str' object does not support item assignment
note

See Python string chapter for more details.

Python Set

Python Set is an unordered collection of unique elements.

  • The set is defined by values separated by commas within curly brackets { }.
  • The elements of a set are unordered.
my_set = {4,1,3,2,5}

# printing set variable
print("my_set = ", my_set)

Since sets are unordered collections, indexing has no meaning. Therefore, the slicing operator [] does not work.

my_set = {1,2,3}
my_set[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

The sets have unique values, so duplicates are deleted automatically.

my_set = {1,2,2,3,3,3}
print(my_set) # print {1, 2, 3}
note

See Python set chapter for more details.

Python Dictionary

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

  • Python Dictionary is used there are a huge amount of data because Dictionaries are optimized for retrieving data.
  • Each key is used to retrieve the respective value (and not vice versa).
  • key-value pairs in a dictionary are not ordered or sortable.

A dictionary is created using curly brackets {}. In addition, you can directly define a dictionary with some key-value pairs

empty_dict= {}
pre_loaded_dict = {"one": 1, "two": 2, "three": 3}

The values are accessed by indicating the key between the slicing operator [key-name].

my_dict = {1:'value','key':2, 'my-key':'my-value'}

print("my_dict[1] = ", my_dict[1])
print("my_dict['key'] = ", my_dict['key'])

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

Output

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

See Python dictionary chapter for more details.

Casting: conversion between data types

Casting in programming is the conversion of a datum from one type to another.

In Python, different data types can be converted to other data types using type conversion functions such as int(), float(), str(), etc.

Conversion from integer to float

float(5)   # 5.0

Conversion from float to integer

Converting float to int truncates the value (making it closer to zero).

int(10.6)   # 10   
int(-10.6) # -10

Conversion to and from string

Conversions to and from string must contain compatible values.

float('2.5') # 2.5
str(25) # '25'

# Generate a ValueError for invalid literal
int('1p')

Conversion of sequence

A sequence can be converted to 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']

Conversion to dictionary

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}

Get class from a variable

The type() function is used 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.

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

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

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

Output

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