Python offers a variety of data types to store and manipulate different kinds of information efficiently. This article explores Python’s built-in data types, their key characteristics, and how they are used in real-world applications. It also covers their benefits and practical examples to help you understand and use them effectively in your programs.
Contents:
- What are Data Types in Python?
- Numeric Data Types in Python
- Sequence Data Types in Python
- Set Data Types in Python
- Mapping Data Types in Python
- Boolean Data Types in Python
- Binary Data Types in Python
- FAQs on Data Types in Python
What are Data Types in Python?
In Python, data types define the kind of values that can be stored and manipulated in a program. They determine the operations that can be performed on the data and how the values are stored in memory. Python provides several built-in data types to handle different kinds of information, such as numbers, text, lists, and more.
Categories of Data Types in Python
Python data types can be broadly classified into the following categories:
| Category | Data Type | Description |
|---|---|---|
| Numeric | int | Whole numbers (e.g., 10, -5, 1000) |
| Numeric | float | Decimal numbers (e.g., 3.14, -0.5) |
| Numeric | complex | Complex numbers (e.g., 2 + 3j) |
| Sequence | str | Text data (e.g., “Hello”, ‘Sanfoundry’) |
| Sequence | list | Ordered, mutable collection (e.g., [1, 2, 3], [“Java”, “Python”]) |
| Sequence | tuple | Ordered, immutable collection (e.g., (1, 2, 3), (“a”, “b”)) |
| Set | set | Mutable set of unique values (e.g., {1, 2, 3}) |
| Set | frozenset | Immutable set of unique values |
| Mapping | dict | Key-value pairs (e.g., {“name”: “Arjun”, “Score”: 85}) |
| Boolean | bool | Can be True or False |
| Binary | bytes | Immutable sequence of bytes |
| Binary | bytearray | Mutable sequence of bytes |
| Binary | memoryview | Memory-efficient view of binary data |
Numeric Data Types in Python
Python provides various numeric data types to handle mathematical operations efficiently. These data types include integers, floating-point numbers, and complex numbers. Python dynamically assigns the data type based on the value assigned to a variable.
1. Integer (int)
Integers in Python are whole numbers that can be positive, negative, or zero. They do not contain any decimal part and are useful in various mathematical operations.
# Integer Example students_count = 50 exams_completed = -3 pending_tasks = 0 print("Students Count:", students_count) print("Exams Completed:", exams_completed) print("Pending Tasks:", pending_tasks)
Output:
Students Count: 50 Exams Completed: -3 Pending Tasks: 0
The variables students_count, exams_completed, and pending_tasks are assigned integer values, representing positive, negative, and zero values.
2. Floating-Point (float)
Floating-point numbers in Python are used to represent real numbers with decimal points or numbers in scientific notation.
# Float Example average_score = 87.5 data_size = 2.5e6 # Equivalent to 2.5 × 10^6 print("Average Score:", average_score) print("Data Size in Bytes:", data_size)
Output:
Average Score: 87.5 Data Size in Bytes: 2500000.0
Floating-point numbers can store decimal values and be expressed in scientific notation.
3. Complex Numbers (complex)
Complex numbers in Python consist of a real part and an imaginary part, represented as a + bj, where a is the real part and b is the imaginary part.
# Complex number (2 is real part, 3j is imaginary part) num = 2 + 3j print(type(num)) print(num.real) print(num.imag)
Output:
<class 'complex'> 2.0 3.0
4. Type Conversion Between Numeric Data Types
Python allows converting one numeric type to another using int(), float(), and complex() functions.
students_score = 85 # Integer score_float = float(students_score) score_complex = complex(students_score) print("Integer to Float:", score_float) print("Integer to Complex:", score_complex)
Output:
Integer to Float: 85.0 Integer to Complex: (85+0j)
5. Mathematical Operations on Numeric Types
Python supports arithmetic operations such as addition, subtraction, multiplication, and division on numeric data types.
a = 10 b = 3 print(a + b) # Output: 13 print(a - b) # Output: 7 print(a * b) # Output: 30 print(a / b) # Output: 3.3333 print(a // b) # Output: 3 (floor division) print(a % b) # Output: 1 (remainder) print(a ** b) # Output: 1000 (10^3)
Sequence Data Types in Python
In Python, sequence data types are used to store collections of items in an ordered manner. They allow indexing, slicing, and iteration over elements. The main sequence types in Python are:
- String (str) – Immutable text sequences
- List (list) – Mutable ordered collection
- Tuple (tuple) – Immutable ordered collection
- Range (range) – Immutable sequence of numbers
1. String (str)
A string is a sequence of Unicode characters enclosed in single, double, or triple quotes. Strings are immutable, meaning their values cannot be changed after creation.
Example:
# String Example text = "Sanfoundry Rocks" print(text) # Output: Sanfoundry Rocks print(text[0]) # Output: S (indexing) print(text[0:10]) # Output: Sanfoundry (slicing)
Common String Operations:
s = "Python" print(s.lower()) # Output: python print(s.upper()) # Output: PYTHON print(s.replace("P", "J")) # Output: Jython print(s + " Programming") # Output: Python Programming (concatenation)
2. List (list)
A list is a mutable collection of items that can hold different data types. Lists allow modifications such as adding, removing, and changing elements.
Example:
my_list = [1, 2, 3, "Python", 4.5] print(my_list[0]) # Output: 1 (indexing) print(my_list[-1]) # Output: 4.5 (negative indexing) print(my_list[1:4]) # Output: [2, 3, 'Python'] (slicing)
3. Tuple (tuple)
A tuple is similar to a list but immutable, meaning elements cannot be modified after creation. Tuples are useful when you need a collection that should not change.
Example:
modules = ("OS", "DBMS", "Networking", "Security") print("Sanfoundry Modules:", modules) print("First Module:", modules[0])
Output:
Sanfoundry Modules: ('OS', 'DBMS', 'Networking', 'Security') First Module: OS
4. Range (range)
The range type is used to generate a sequence of numbers efficiently. It is commonly used in loops.
Example:
for i in range(1, 6): print("Question", i)
Output:
Question 1 Question 2 Question 3 Question 4 Question 5
Set Data Types in Python
In Python, a set is an unordered collection of unique elements. It does not allow duplicate values and supports operations like union, intersection, and difference. There are two types of sets in Python:
- Set (set) – Mutable, unordered collection of unique elements.
- Frozen Set (frozenset) – Immutable version of a set.
1. Set (set)
A set is defined using curly braces {} or the set() function. It automatically removes duplicate values and does not maintain any specific order.
Example:
courses = {"Python", "Java", "C++", "Python"} print("Available Courses:", courses) courses.add("SQL") # Add new element print("Updated Courses:", courses)
Output:
Available Courses: {'Python', 'Java', 'C++'} Updated Courses: {'Python', 'Java', 'C++', 'SQL'}
2. Frozen Set (frozenset)
A frozenset is an immutable version of a set. Once created, its elements cannot be modified.
modules = frozenset(["OS", "DBMS", "Networking"]) print("Frozen Set Modules:", modules)
Output:
Frozen Set Modules: frozenset({'OS', 'DBMS', 'Networking'})
3. Set Operations
Python provides various operations for sets, such as union, intersection, difference, and symmetric difference.
# Set Operations Example set1 = {"Python", "Java", "C"} set2 = {"Java", "SQL", "Python"} # All unique elements print("Union:", set1.union(set2)) # Common elements print("Intersection:", set1.intersection(set2)) # Elements in set1 not in set2 print("Difference:", set1.difference(set2)) # Elements not common in both sets print("Symmetric Difference:", set1.symmetric_difference(set2))
Output:
Union: {'Python', 'Java', 'C', 'SQL'} Intersection: {'Python', 'Java'} Difference: {'C'} Symmetric Difference: {'C', 'SQL'}
4. Adding and Removing Elements
Sets allow adding and removing elements using add(), remove(), and discard() methods.
subjects = {"Maths", "Physics", "Chemistry"} subjects.add("Biology") subjects.remove("Maths") print("Updated Subjects:", subjects) subjects.discard("English") # No error if element not found print("Final Subjects:", subjects)
Output:
Updated Subjects: {'Physics', 'Biology', 'Chemistry'} Final Subjects: {'Physics', 'Biology', 'Chemistry'}
Mapping Data Types in Python
Dictionary (dict)
A dictionary in Python stores key-value pairs and allows fast lookups. Keys must be unique and immutable, while values can be of any type.
Example:
sanfoundry_courses = {"Python": "Intermediate", "Java": "Advanced"} print("Python Course Level:", sanfoundry_courses["Python"])
Output:
python Course Level: Intermediate
Adding and Modifying Elements
New key-value pairs can be added or modified.
sanfoundry_courses = {"Python": "Intermediate", "Java": "Advanced"} sanfoundry_courses["C++"] = "Beginner" # Add sanfoundry_courses["Java"] = "Expert" # Modify print(sanfoundry_courses)
Output:
{'Python': 'Intermediate', 'Java': 'Expert', 'C++': 'Beginner'}
Removing Elements
Use pop(), del, or popitem() to remove elements.
sanfoundry_courses.pop("Java") print(sanfoundry_courses)
Boolean Data Types in Python
The Boolean (bool) data type in Python represents True or False values. It is commonly used in logical operations, conditions, and comparisons.
is_sanfoundry_useful = True print("Is Sanfoundry useful?", is_sanfoundry_useful) # Boolean as numbers print("True as int:", int(True)) print("False as int:", int(False))
Output:
Is Sanfoundry useful? True True as int: 1 False as int: 0
Comparison and Logical Operations
print(10 > 5) # Output: True print(3 == 5) # Output: False print(7 != 2) # Output: True
Boolean Conversion
Values can be converted to Boolean using the bool() function.
print(bool(0)) # False print(bool(5)) # True print(bool("")) # False print(bool("Sanfoundry")) # True
Boolean in Conditional Statements
Booleans are often used in if-else statements to control program flow.
# Conditional Example is_sanfoundry_free = True if is_sanfoundry_free: print("Access Sanfoundry resources for free!") else: print("Subscription required.")
Output:
Access Sanfoundry resources for free!
Binary Data Types in Python
Binary data types in Python represent data in binary (base-2) format, which consists of 0s and 1s. These data types include bytes, bytearray, and memoryview.
1. Bytes (bytes)
bytes is an immutable sequence of bytes that stores binary data. It is commonly used for handling binary files such as images and audio.
sanfoundry_data = b"Python" print("Bytes Data:", sanfoundry_data) # Access byte by index print("First Byte:", sanfoundry_data[0])
Output:
Bytes Data: b'Python' First Byte: 80
2. Bytearray (bytearray)
bytearray is a mutable sequence of bytes, allowing modification of its elements.
sanfoundry_bytes = bytearray(b"Java") sanfoundry_bytes[0] = 80 # Modify first byte to ASCII of 'P' print("Modified Bytearray:", sanfoundry_bytes)
Output:
Modified Bytearray: bytearray(b'Pava')
3. Memoryview (memoryview)
memoryview provides a view of the binary data without copying, allowing efficient data manipulation.
sanfoundry_data = b"SQL" view = memoryview(sanfoundry_data) # ASCII of 'S' print("First Byte:", view[0])
Output:
First Byte: 834. Converting Data to Binary Types
Use bytes(), bytearray(), or memoryview() to convert data.
sanfoundry_list = [80, 121, 116, 104, 111, 110] sanfoundry_bytes = bytes(sanfoundry_list) print("Converted to Bytes:", sanfoundry_bytes) sanfoundry_bytearray = bytearray(sanfoundry_list) print("Converted to Bytearray:", sanfoundry_bytearray)
Output:
Converted to Bytes: b'Python' Converted to Bytearray: bytearray(b'Python')
FAQs on Data Types in Python
1. What are data types in Python?
Data types in Python define the type of values that variables can store. They determine what kind of operations can be performed on the data and how values are stored in memory.
2. How does Python handle data types?
Python is dynamically typed, meaning you don’t need to declare a variable’s type explicitly. Python automatically assigns the type based on the value.
3. What is the difference between a list and a tuple?
A list is mutable (modifiable), while a tuple is immutable (cannot be changed after creation). Lists use square brackets [], and tuples use parentheses ().
4. What is the difference between a set and a dictionary?
A set is an unordered collection of unique elements, while a dictionary stores key-value pairs, where each key must be unique.
5. Can we change the data type of a variable in Python?
Yes, Python allows type conversion using functions like int(), float(), str(), list(), etc. This process is called type casting.
6. What is a frozenset in Python?
A frozenset is an immutable version of a set, meaning its elements cannot be changed after creation. It is useful for ensuring a collection remains unchanged.
7. What are binary data types in Python?
Binary types include bytes, bytearray, and memoryview, which are used for handling binary data like images, files, and network communication.
8. What is the default type of input() function in Python?
The input() function returns user input as a string (str) by default, even if the user enters numbers. To convert it, use int(input()) or float(input()).
Key Points to Remember
Here is the list of key points we need to remember about “Python Data Types”.
- Python has several built-in data types categorized into Numeric, Sequence, Set, Mapping, Boolean, and Binary types.
- Numeric data types include int (whole numbers), float (decimal numbers), and complex (numbers with real and imaginary parts).
- Sequence data types include str (immutable text), list (mutable ordered collection), tuple (immutable ordered collection), and range (sequence of numbers).
- Set data types consist of set (mutable, unordered collection of unique elements) and frozenset (immutable version of a set).
- Mapping data type in Python is dict, which stores key-value pairs and allows fast lookups, modifications, and deletions.
- Boolean (bool) represents True or False values, while Binary data types (bytes, bytearray, memoryview) handle binary data efficiently.