Data Types in Python

Learn about the different data types in Python and how to use them effectively in your programs.

30 min read
Beginner

Introduction to Data Types

Data types are classifications that specifies which type of value a variable has. It defines the kind of mathematical, relational or logical operations that can be applied to the variable.

Python contains several data types to make it easier for programmers to write functional and replicable programs. The different data types used in Python are listed below:

Common Data Types in Python
Name
Data Type
Example
Python Integerint123, 66, 222
Python Floatfloat2.4, 3.21, 4.666
Python String (str)str'Apple', 'Ball'
Python List (list)list['Python', 'C', 'C++'], ['Nepal', 'USA']
Python Tuple (tuple)tuple('Python', 'C', 'C++'), ('Nepal', 'USA')
Python Dictionary (dict)dict{'Name':'John'}, {'id':1, 'age': 48}
Python Set (set)set{'a', 'b', 'c'}, {1,2,3,4}
Python Boolean (bool)boolTrue, False

Now, let us move onto discuss the characteristics of all of these data types one-by-one.

Numbers in Python

Numbers are categorized into integers (int) and floating point numbers (float) in Python. Integers are numbers without a decimal point whereas floats are numbers with a decimal point.

python
# Integer
100
python
# Float
100.0

We can perform all of the arithmetic operations we've learnt in the previous lesson on integers as well as floats. However, the result of such operations can be an integer or a float depending on the type of operation.

python
# Integer + Integer results in Integer
10 + 10
python
# Integer + Float results in Float
10 + 10.0
python
# Integer * Integer results in Integer
2 * 4
python
# Integer * Float results in Float
2 * 4.0
python
# Integer / Integer results in Float
4 / 2

Python string (str)

A string is a sequence of characters and they are surrounded by either single or double quotation marks. For example,

python
# A string made using single quotation marks
x = 'Apple'

# A string made using double quotation marks
y = "Mango"

print(x)
print(y)

The characters of a string are indexed starting from 0.

python
x = 'Apple'

# Accessing indexes of a string
print(x[0])  # Output: A
print(x[1])  # Output: p
print(x[3])  # Output: l
python
# Negative indexing starts from the end
x = 'Apple'
print(x[-1]) # Output: e
print(x[-2]) # Output: l

While we are on the topic of indexes, let's also look at index slicing where we can use the square brackets ([]) and colons [:] to dictate slices of a string we want to extract.

Index slicing uses the format [start:stop:step] where:

  • start: The starting index of the slice (inclusive).
  • stop: The ending index of the slice (exclusive).
  • step: The step size or interval between each index in the slice.

If start is omitted, it defaults to the beginning of the string. If stop is omitted, it defaults to the end of the string. If step is omitted, it defaults to 1.

python
# Index slicing [start:stop:step]
x = 'Apple'
print(x[:])  # Output: Apple
print(x[0:3]) # Output: App
print(x[1:4]) # Output: ppl
print(x[1:])  # Output: pple
print(x[:3])  # Output: App
print(x[1:-1]) # Output: ppl
print(x[0:5:2]) # Output: Ape
print(x[::2]) # Output: Ape (same as above)

There are multiple operations that can be performed on strings in Python:

python
# Intializing x and y
x = "Apple"
y = "Mango"

print(x + y) # Output: AppleMango (Concatenation)
print(x * 3) # Output: AppleAppleApple (Repetition)

We can also use a set of methods that you can use on strings in Python.

python
x = 'apple'
print(x.upper())  # Output: APPLE
print(x.lower())  # Output: apple
print(x.replace('a', 'e'))  # Output: epple
print(x.find('p'))  # Output: 1 (index of first occurrence of 'p')
print(x.capitalize())  # Output: Apple
print(x.count('p'))  # Output: 2 (number of occurrences of 'p'
print(x.split('p'))  # Output: ['a', '', 'le'] (splits string at 'p')
print(x.strip('App')) # Output: le (removes 'App' from start)

We can also format strings with additional characters.

python
z = "I speak {}"
print(z.format("Python"))
python
z = "I speak {} {}"
z.format("the Python", "language.")
python
z = "I speak {a} {b}"
z.format(b = "language.", a = "the Python")

A shortcut to string formatting is by using f strings also written as f"I speak {var1} {var2}".

python
a = "the Python"
b = "language."
z = f"I speak {a} {b}"
print(z)

Python List (list)

Lists are array sequences that store a collection of items of the same or different data types.

In a list, the elements are surrounded by square brackets [ ] and the indexing of these elements starts at 0. This means that the first item has an index of 0, the second item has an index of 1, and so on.

python
# list1 storing integers
list1 = [1, 2, 3, 4, 5]

# list2 storing different data types
list2 = [1.0, 2, 3, 4.0, '5']

print(list1)
print(list2)

Lists can be indexed and sliced similar to strings.

python
squares = [1, 4, 9, 16, 25]
print(squares[0])  # Output: 1
print(squares[-1]) # Output: 25
print(squares[1:4])  # Output: [4, 9, 16]
print(squares[1:-1])  # Output: [4, 9, 16]

We can also update the elements of a list at particular indexes.

python
squares = [1, 4, 9, 16, 25]
squares[0] = 0
print(squares)
python
squares = [1, 4, 9, 16, 25]
squares[1:3] = [1, 1] # Changing a slice of a list
print(squares)

Python Tuple (tuple)

Tuples are array sequences that store a collection of items of the same or different data types. The elements of a tuple are surrounded by round brackets ( ).

python
# tuple1 storing integers
tuple1 = (1, 2, 3, 4, 5)

# tuple2 storing different data types
tuple2 = (1.0, 2, 3, 4.0, '5')

print(tuple1)
print(tuple2)

Tuples are like lists, except for the fact that the elements of a tuple cannot be changed after initialization.

python
squares = (1, 4, 9, 16, 25) 

# Running this will raise an error
squares[0] = 0

Python Dictionary (dict)

A dictionary is a set of key-value pairs and every key in a dictionary must be unique. The elements of a dictionary are surrounded by curly brackets, i.e., { }.

python
# dict1 is a dictionary
dict1 = {'key1':'value1', 'key2':'value2'}
print(dict1)

There are multiple operations that can be performed on a dictionary in Python:

python
costs_dict = {'Kitkat':1300, 'Caramel':1800, 'Chocolate':1000, 'Mango':3600} 
print(costs_dict) # Printing dict
print(costs_dict.keys()) # Printing all keys
print(costs_dict.values()) # Printing all values
print(costs_dict['Chocolate']) # Accessing value using key

We can also update the elements of a dictionary using keys.

python
costs_dict = {'Kitkat':1300, 'Caramel':1800, 'Chocolate':1000, 'Mango':3600} 
costs_dict['Kitkat'] = 2000
print(costs_dict)

We can add new key value pairs to the dictionary as well after initialization.

python
costs_dict = {'Kitkat':1300, 'Caramel':1800, 'Chocolate':1000, 'Mango':3600} 
costs_dict['Banana'] = 1500
print(costs_dict)

We can also delete key value pairs from the dictionary using the del keyword,

python
costs_dict = {'Kitkat':1300, 'Caramel':1800, 'Chocolate':1000, 'Mango':3600} 
del costs_dict['Caramel']
print(costs_dict)

Python Set (set)

A set is an unordered collection of non-duplicated elements. The elements of a set are surrounded by curly brackets { } but they do not exist as key-value pairs like in a dictionary.

python
# set1 is a set
set1 = {1, 2, 3, 4, 5}

print(set1)

The elements of a set is non-indexable unlike lists or tuples since the elements are not ordered.

python
set1 = {1, 2, 3, 4, 5}

# Running this will cause an error
set1[0]

Set also supports mathematical operations like union, intersection, difference, and symmetric difference.

python
x = {'l', 'm', 'z', 'c', 'a', 'e', 'i', 'k'}
y = {'l', 'm', 'z', 'c', 'a'}

print(x - y) # Difference: elements in x but not in y
print(y - x) # Difference: elements in y but not in x
print(x & y) # Intersection: elements in both x and y
print(x | y) # Union: all unique elements in x and y
print(x ^ y) # Symmetric Difference: elements in either x or y but not in both

Python Boolean

A Python Boolean represents either the value ‘True’ or ‘False’.

python
# bool1 is a boolean
bool1 = True

# bool2 is a boolean
bool2 = False

print(bool1)
print(bool2)

Booleans are mostly generated when evaluating expressions such as,

python
print(2 == 2)
print(4 < 2)

Test your knowledge

🧠 Knowledge Check
1 / 15

What is a data type in Python?