Data Types in Python - 8 Data Types in Python With Examples

Data Types in Python - 8 Data Types in Python With Examples

05 Feb 2025
Beginner
29.1K Views
33 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

Data Type in Python

Data types in Python define the kind of value a Variable in Pythoncan hold. Python is a dynamically typed language, which means you don’t need to declare the data type explicitly. It supports various built-in data types like numbers, strings, lists, tuples, and dictionaries, making it versatile for different programming tasks.If you’re preparing to deepen your knowledge of Python data types, it’s essential to understand their core functionalities, operations, and how they interact in Python programs.

In this Python tutorial, we’ll explore the most commonly used data types in Python and provide practical insights into their applications.

What is a Data Type in Python?

A data type in Python specifies the kind of value a variable can store. It determines the operations that can be performed on the variable. Python’s dynamic typing allows variables to hold values of any data type without explicit declaration.

Key Features of Data Types in Python

  • Dynamic Typing: Python automatically assigns data types at runtime.
  • Built-in Types: Includes numeric, text, sequence, mapping, set, boolean, and binary types.
  • Type Checking: Use the type()Python function to check the data type of a variable.
  • Type Conversion: Convert between data types using functions like int(), float(), and str().
Read More: Python Interview Questions and Answers

Types of Data Types in Python

Python has various built-in data types, which will be discussed in this article:

  1. Numeric - int, float, complex
  2. String - str
  3. Sequence - list, tuple, range
  4. Binary - bytes, bytearray, memoryview
  5. Mapping - dict
  6. Boolean - bool
  7. Set - set, frozenset
  8. None - NoneType

Types of Python Data Types

1. Numeric Data Types in Python

When you work with numbers in Python, you use numeric data types. They let you handle different types of numeric values like whole numbers, decimals, or even complex numbers. Wouldn’t you want to know which numeric types Python supports?

Types of Numeric Data in Python

  • int: Used for whole numbers. These are signed integers like 10, -5, or 0.
  • long: Python 2 supports long integers, which can represent really large numbers, including octal and hexadecimal. (In Python 3, all integers are of type int.)
  • float: Used for decimal numbers, like 3.14 or -0.99.
  • complex: Represents numbers with a real and imaginary part, like 3+4j.

Here are some examples of different types of numbers-

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j

Example of Numeric Data Type in Python Compiler

# integer variable.
a=150
print("The type of variable having value", a, " is ", type(a))
# float variable.
b=20.846
print("The type of variable having value", b, " is ", type(b))
# complex variable.
c=18+3j
print("The type of variable having value", c, " is ", type(c))

Output

The type of variable having value 150 is <class 'int'>
The type of variable having value 20.846 is <class 'float'>
The type of variable having value (18+3j) is <class 'complex'>

Explanation

  • The program defines three variables: a, b, and c, with integer, float, and complex values respectively.
  • The type() function is used to determine the data type of each variable.
  • It prints the variable's value and its corresponding data type to the console.
  • This helps in understanding how Python recognizes and categorizes different types of data.
Read More: Python Developer Salary

2. Python String Data Type

If you’re working with text in Python, you’ll use the string data type. A string is a collection of characters enclosed in single, double, or even triple quotes. Isn’t it great how Python makes handling text so easy?

Key Features of Python Strings

  • Immutable: Once you create a string, you can’t change its content.
  • Multi-line Support: Use triple quotes (''' or """) for strings that span multiple lines.
  • Indexing and Slicing: Access individual characters or parts of the string using indices.
  • String Methods: Python offers built-in methods like lower(), upper(), and replace() for string manipulation.

Example of String Data Type in Python

  
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string stating from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

Output

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Explanation

  • The program demonstrates string operations in Python.
  • It shows how to print the complete string, access specific characters, extract substrings using slicing in Python, repeat the string, and concatenate it with another string using the string in Python.

3. Python List Data Type

When you need to store multiple items in a single variable, you’ll use the list data type. A list in Python can hold items of different data types, and you can easily modify it. Isn’t that flexible? For more details, you can explore how to work with lists in Python.

Key Features of Python Lists

  • Ordered: Lists maintain the order of items as you add them.
  • Mutable: You can modify, add, or remove items after creating the list.
  • Supports Multiple Data Types: A single list can hold integers, strings, and even other lists.
  • Built-in Methods: Use methods like append(), remove(), and sort() to manipulate lists.

Example of List Data Type in Python

list = [ 'abcd', 786 , 2.23, 'Scholar-Hat', 70.2 ]
tinylist = [123, 'Scholar-Hat']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd 
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

Output

['abcd', 786, 2.23, 'Scholar-Hat', 70.2]
abcd
[786, 2.23]
[2.23, ‘Scholar-Hat', 70.2]
[123, 'Scholar-Hat', 123, 'john']
['abcd', 786, 2.23, 'Scholar-Hat', 70.2, 123, 'Scholar-Hat']

Explanation

  • This program demonstrates list operations in Python, such as printing the entire list, accessing specific elements, slicing the list, repeating it, and concatenating two lists.
  • It uses two lists: list and tinylist, and performs various operations like slicing and concatenation.

4. Python Tuple Data Type

A tuple in Python is an ordered list of elements, just like a list. However, unlike lists, tuples are immutable, meaning that once created, they cannot be changed. Isn’t it great to have an ordered, unchangeable collection of items? Tuples are stored using () parentheses, and you can access items in a tuple using their index, just like with lists.

Key Features of Python Tuples

  • Ordered: Tuples maintain the order of elements as you add them.
  • Immutable: Once created, you cannot modify, add, or remove items.
  • Supports Multiple Data Types: A tuple can hold items of different data types, like integers, strings, or even other tuples.
  • Indexing: You can access elements by their index number, similar to how you use indexing with lists.

Example of Tuple Data Type in Python

  
tuple = ( 'abcd', 786 , 2.23, 'Scholar-Hat', 70.2 )
tinytuple = (123, 'Scholar-Hat')
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd 
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples

Output

('abcd', 786, 2.23, 'Scholar-Hat', 70.2)
abcd
(786, 2.23)
(2.23, 'Scholar-Hat', 70.2)
(123, ‘Scholar-Hat', 123, 'Scholar-Hat')
('abcd', 786, 2.23, 'Scholar-Hat', 70.2, 123, 'Scholar-Hat')

Explanation

  • The program defines two tuples: tuple and tinytuple, containing mixed data types.
  • print(tuple): Prints the complete tuple tuple.
  • print(tuple[0]): Prints the first element of the tuple, which is 'abcd'.
  • print(tuple[1:3]): Prints elements starting from index 1 to 2 (2nd to 3rd element), which are 786 and 2.23.
  • print(tuple[2:]): Prints elements starting from index 2 onward, which are 2.23, 'Scholar-Hat', 70.2.
  • print(tinytuple * 2): Prints the contents of tinytuple twice, resulting in (123, 'Scholar-Hat', 123, 'Scholar-Hat').
  • print(tuple + tinytuple): Concatenates and prints the two tuples together, resulting in ('abcd', 786, 2.23, 'Scholar-Hat', 70.2, 123, 'Scholar-Hat').

5. Python Range Data Type

The range data type in Python represents a sequence of numbers commonly used in loops in Python. It generates numbers starting from a given number, up to but not including another number. Isn’t it convenient when you need to iterate over a specific range of values without manually creating a list?

Key Features of Python Range

  • Efficient: It generates numbers on the fly, which is memory efficient compared to lists.
  • Supports Indexing: You can access individual elements of a range using indexing.
  • Customizable: You can specify the start, stop, and step values when creating a range.
  • Used in Loops: Commonly used in Python for loops to iterate over a sequence of numbers.

Example of Range Data type in Python

for i in range(1, 5):
 print(i)

Output

1
2
3
4
for i in range(1, 5): print(i)

6. Python Dictionary Data Type

A dictionary in Python is a collection of key-value pairs. It allows you to store data in a way that associates a unique key with a corresponding value. Isn’t it useful to quickly look up data based on a unique identifier?

Key Features of Python Dictionaries

  • Unordered: The items in a dictionary are not stored in any particular order.
  • Mutable: You can modify, add, or remove key-value pairs after the dictionary is created.
  • Unique Keys: Each key in a dictionary is unique, and it maps to a specific value.
  • Efficient Lookup: You can quickly retrieve the value associated with a key.

Example of Dictionary Data Type in Python

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'Scholar-Hat','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

Output

This is one
This is two
{'name': 'Scholar-Hat', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['Scholar-Hat', 6734, 'sales'])

Explanation

  • This program creates two dictionaries: dict and tinydict, with key-value pairs.
  • print(dict['one']): Prints the value associated with the key 'one' from the dictionary dict.
  • print(dict[2]): Prints the value associated with the key 2 from the dictionary dict.
  • print(tinydict): Prints the entire tinydict dictionary.
  • print(tinydict.keys()): Prints all the keys in tinydict.
  • print(tinydict.values()): Prints all the values in tinydict.

7. Python Boolean Data Type

The boolean data type in Python represents one of two possible values: True or False. It is commonly used for conditional statements, where decisions are made based on whether a condition is true or false. Wouldn’t you agree that it’s essential for controlling the flow of a program?

Key Features of Python Booleans

  • True or False: The two boolean values are True and False.
  • Conditional Logic: Used extensively in if and while statements to control program flow.
  • Result of Comparisons: Comparisons between values often result in a boolean value.
  • Logical Operations: You can use logical operators in Python like and, or, and not with boolean values.

Example of Boolean Data Type in Python

a = True
# display the value of a
print(a)

# display the data type of a
print(type(a))

Output

true
<class 'bool'>

Explanation

  • This program defines a variable a and assigns it the boolean value True.
  • print(a): Displays the value of a, which is True.
  • print(type(a)): Displays the data type of a, which is <class 'bool'>.

8. Python Set Data Type

A set in Python is an unordered collection of unique elements. It’s useful when you need to store values without duplicates and perform operations like union, intersection, and difference. Isn’t it efficient to have a collection where each element is unique and easy to manipulate?

Key Features of Python Sets

  • Unordered: Sets do not maintain any order of elements.
  • Unique Elements: A set automatically removes duplicate values, so each element is unique.
  • Mutable: You can add or remove elements from a set after it is created.
  • Supports Set Operations: Python sets support operations like union(), intersection(), and difference().

Example of Set Data Type in Python

        my_set = {1, 2, 3, 4, 5}
print(my_set)

Output

{1, 2, 3, 4, 5}

Explanation

  • This program defines a set my_set containing the elements 1, 2, 3, 4, 5.
  • print(my_set): Displays the content of the set my_set.
  • Since sets are unordered collections, the elements might appear in any order when printed.
What is the data type conversion function?
  • In Python, the process of converting an object's data type from one type to another is referred to as data type conversion.
  • In Python, there are two primary methods for converting data types:
    1. Implicit Type Conversion
    2. Explicit Type Conversion

Example of Data Type Conversion Function in Python Online Compiler

a = str(1) # a will be "1" 
b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"
print (a)
print (b)
print (c)

In this code, the numbers 1 and 2.2 are converted to string representations and assigned to variables 'a' and 'b', respectively. The string "3.3" is already present in variable "c". Following that, it prints the values of "a," "b," and "c," producing the output.

Output

1
2.2
3.3

Explanation

  • This program converts different data types into strings using the str() function.
  • a = str(1): Converts the integer 1 to the string "1".
  • b = str(2.2): Converts the float 2.2 to the string "2.2".
  • c = str("3.3"): Converts the string "3.3" (which is already a string) to "3.3".
  • print(a), print(b), print(c): Prints each of the string variables a, b, and c.

How to Check Data Type in Python?

Do you want to know the type of a variable in Python? You can use the type() function to determine the data type of any variable. Isn’t it simple and straightforward? This function tells you the exact type of data stored in a variable.

Key Steps to Check Data Type

  • Use the type() function and pass the variable as an argument.
  • It returns the data type, such as int, float, str, etc.
  • You can also use isinstance() to check if a variable belongs to a specific data type.

Example:


value = 10
print(type(value))  # Output: 

Explanation

  • This program defines a variable value and assigns it the integer 10.
  • print(type(value)): Displays the data type of value, which is <class 'int'>.
  • This confirms that the data type of the variable value is integer.
Summary

This article explained the different data types in Python and their significance. From understanding numeric types such as int and float to exploring collections like lists, tuples, and dictionaries, you’ve learned how Python handles data efficiently. Whether you're a beginner or advancing your Python journey, mastering these data types is necessary for writing robust and scalable programs. Want to deepen your Python knowledge? Enroll in the Scholarhat Python For Data Science and AI Certification Training today and enhance your expertise in Python programming!

Looking to expand your programming skills for free? Check out these Scholarhat Free Courses:

Test Your Knowledge of Data Types in Python!

Q 1: What is the type of the value `10` in Python?

  • (a) float
  • (b) int
  • (c) str
  • (d) list

Q 2: What is the type of the value `'Hello, world!'` in Python?

  • (a) list
  • (b) str
  • (c) tuple
  • (d) bool

Q 3: Which of the following is a mutable data type in Python?

  • (a) str
  • (b) tuple
  • (c) list
  • (d) int

Q 4: What is the type of the value `3.14` in Python?

  • (a) int
  • (b) float
  • (c) str
  • (d) bool

Q 5: Which of the following data types is used to represent a collection of unique elements in Python?

  • (a) list
  • (b) tuple
  • (c) set
  • (d) dict

FAQs

For mathematical operations in Python with numeric data types, use operators like +, -, *, and /.

When calculating with both real and fictional components, use complex numbers.

Use tools like str.format() or f-strings to manipulate and format strings.

Slicing, concatenating, and searching with tools like find() and split() are common string operations.

Lists can be modified by adding with append() or extend(), removing with remove() or pop(), or using list comprehensions.

Use the "in" keyword or the index() method on lists to verify an element's presence.

Lists, tuples, and strings are examples of sequence types.

Python Tuples are immutable (unchangeable), whereas lists are mutable (may be changed).

If you want to loop through a list of numbers, use the range data type.

Use list(range()) to turn a Python Range into a list or a for loop to iterate directly.

There are numerous data types available in Python, including int, float, str, bool, list, tuple, dict, set, and others.

Lists are an example of a mutable data type, while tuples are an example of an immutable type.

Random type conversions, changeable default parameters, and data loss during type conversions are common hazards. To prevent these problems, use explicit type handling.

Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this