Python offers several data types, including numbers (integers and floating-point), lists , dictionaries (for key-value pairs), booleans (True or False ), and sets (for unique values ). These data types help store and process data efficiently.
Saranya is a data scientist working on a project to gather and analyze data. As part of her analysis, she needed to understand the different data types she would be dealing with. Saranya came across a book ???? that contained information about the different data types.
The book explained that data could be classified as one of four types: integers , floats, strings 🔤 and booleans. Saranya discovered that an integer is a whole number like 3 or -25; a float is a number with decimals like 3.1415; strings are words or phrases contained within quotation marks like "Hello World"; and booleans can only have two possible values: true ✅ and false ❌.
The book also explained how each type of data has its unique properties and how they can be used in various ways. For example, Saranya learned that integers could be added together to find the sum of two integers, but multiplying an integer by another integer will produce another integer. Saranya found a similar book 📚 that talked about the types of data that can be classified as resources.
The resource type in the book is called a "resource locator" because it will tell Saranya where to find the resources she needs, which make up her project . Resources are divided into four categories: strings, floats, booleans, and dates . A string is a text contained within quotation marks like "Hello World," whereas booleans can only have two values: true or false . At the same time, dates are numerical representations of a specific date .
💡 Did you Know ? In Python, the data types are also classified based on their mutability. Mutable data types can be changed after creation, while immutable data types cannot be changed after creation.
Python is a high-level, object-oriented programming language that provides a wide range of data types to aid in developing numerous applications.
Category | Data Type | Description |
---|---|---|
Numeric Types | int | Integers of unlimited size. |
float | Floating-point numbers (decimal numbers). | |
complex | Complex numbers in the form a + bj. | |
Sequence Types | list | Mutable sequences, typically used to store collections. |
str | Immutable sequences of Unicode characters (strings). | |
tuple | Immutable sequences, used to store collections. | |
range | Immutable sequences of numbers, commonly used for looping. | |
Mapping Type | dict | Mutable mappings of keys to values (dictionaries). |
Set Types | set | Unordered collections of unique elements (mutable). |
frozenset | Immutable versions of sets. | |
Boolean Type | bool | Boolean values True or False. |
Binary Types | bytes | Immutable sequences of bytes. |
bytearray | Mutable sequences of bytes. | |
memoryview | Memory views of binary data without copying it. | |
None Type | NoneType | Represents the absence of a value (None). |
Numeric data types are data types that represent numbers, such as integers and floating point numbers. They are used in programming and databases to store and manipulate numerical values. The most common numeric data types in Python are:
Example:
# Create integers positive_int = 42 negative_int = -99 large_int = 12345678901234567890 # Arithmetic operations sum_int = positive_int + negative_int print("Sum:", sum_int) # Check the type print(type(positive_int)) |
Output:
Sum: -57 <class 'int'> |
Example:
# Create floats pi = 3.14159 negative_float = -2.71828 # Arithmetic operations product = pi * negative_float print("Product:", product) # Check the type print(type(pi)) |
Output
Product: -8.539721265199999 <class 'float'> |
Example:
# Create complex numbers complex_num1 = 2 + 3j complex_num2 = 5 - 4j # Arithmetic operations sum_complex = complex_num1 + complex_num2 print("Sum:", sum_complex) # Access real and imaginary parts print("Real part:", complex_num1.real) print("Imaginary part:", complex_num1.imag) # Check the type print(type(complex_num1)) |
Output:
Sum: (7-1j) Real part: 2.0 Imaginary part: 3.0 <class 'complex'> |
In Python, sequence data types refer to objects that hold a collection of items, such as strings, lists, and tuples. These objects can be indexed and sliced and have various methods for modifying and manipulating their contents.
Example:
# Create a string greeting = "Hello, World!" print(greeting) # Access individual characters first_char = greeting[0] print("First character:", first_char) # String concatenation new_greeting = greeting + " How are you?" print(new_greeting) # Check the type print(type(greeting)) |
Output:
Hello, World! First character: H Hello, World! How are you? <class 'str'> |
Example:
# Create a list fruits = ['apple', 'banana', 'cherry'] # Access elements print("First fruit:", fruits[0]) # Modify elements fruits[1] = 'blueberry' print("Modified list:", fruits) # Add elements fruits.append('date') print("Extended list:", fruits) # Check the type print(type(fruits)) |
Output:
First fruit: apple Modified list: ['apple', 'blueberry', 'cherry'] Extended list: ['apple', 'blueberry', 'cherry', 'date'] <class 'list'> |
Example:
# Create a tuple coordinates = (10.0, 20.0) # Access elements x = coordinates[0] y = coordinates[1] print(f"X: {x}, Y: {y}") # Attempting to modify elements (will raise an error) try: coordinates[0] = 5.0 except TypeError as e: print("Error:", e) # Check the type print(type(coordinates)) |
Output:
X: 10.0, Y: 20.0 Error: 'tuple' object does not support item assignment <class 'tuple'> |
Example:
# Create a range numbers = range(5) # Convert range to list for display number_list = list(numbers) print("Number list:", number_list) # Iterate over range for i in range(3, 8): print("Number:", i) # Check the type print(type(numbers)) |
Output:
Number list: [0, 1, 2, 3, 4] Number: 3 Number: 4 Number: 5 Number: 6 Number: 7 <class 'range'> |
A dictionary in Python is an unordered set of key-value pairs. Keys identify elements in the dictionary . Values can be any Python object. Dictionaries are mutable , changeable, and indexed for easy, fast access and modification . Dictionaries map keys to values like a dictionary maps words to definitions .
Syntax:
Loading...
Examples:
Loading...
In Python, booleans represent either True or False values. They are crucial for controlling program flow with conditional statements like if and else.
Example:
# Boolean values is_active = True is_closed = False # Logical operations result = is_active and not is_closed print("Result:", result) # Boolean from expressions comparison = 10 > 5 print("10 > 5:", comparison) # Check the type print(type(is_active)) |
Output:
Result: True 10 > 5: True <class 'bool'> |
Example:
# Create a set unique_numbers = {1, 2, 3, 2, 1} print("Unique numbers:", unique_numbers) # Add elements unique_numbers.add(4) print("After adding 4:", unique_numbers) # Set operations set_a = {1, 2, 3} set_b = {3, 4, 5} union_set = set_a.union(set_b) intersection_set = set_a.intersection(set_b) print("Union:", union_set) print("Intersection:", intersection_set) # Check the type print(type(unique_numbers)) |
Output:
Unique numbers: {1, 2, 3} After adding 4: {1, 2, 3, 4} Union: {1, 2, 3, 4, 5} Intersection: {3} <class 'set'> |
Example:
# Create a frozenset frozen_set = frozenset([1, 2, 3, 2, 1]) print("Frozen set:", frozen_set) # Attempting to modify (will raise an error) try: frozen_set.add(4) except AttributeError as e: print("Error:", e) # Set operations set_c = {2, 3, 4} union_frozen = frozen_set.union(set_c) print("Union with set:", union_frozen) # Check the type print(type(frozen_set)) |
Output:
Frozen set: frozenset({1, 2, 3}) Error: 'frozenset' object has no attribute 'add' Union with set: frozenset({1, 2, 3, 4}) <class 'frozenset'> |
Example:
# Create bytes byte_data = b'Hello, Bytes!' print("Byte data:", byte_data) # Access elements first_byte = byte_data[0] print("First byte:", first_byte) # Iterate over bytes for b in byte_data: print(b, end=' ') print() # Check the type print(type(byte_data)) |
Output:
Byte data: b'Hello, Bytes!' First byte: 72 72 101 108 108 111 44 32 66 121 116 101 115 33 <class 'bytes'> |
Example:
# Create bytearray mutable_bytes = bytearray(b'Hello') print("Original bytearray:", mutable_bytes) # Modify elements mutable_bytes[0] = ord('h') print("Modified bytearray:", mutable_bytes) # Convert to bytes bytes_converted = bytes(mutable_bytes) print("Converted to bytes:", bytes_converted) # Check the type print(type(mutable_bytes)) |
Output:
Original bytearray: bytearray(b'Hello') Modified bytearray: bytearray(b'hello') Converted to bytes: b'hello' <class 'bytearray'> |
Example:
# Create a bytearray data = bytearray('ABC', 'utf-8') print("Original data:", data) # Create a memoryview view = memoryview(data) print("Memoryview:", view) # Modify data through memoryview view[1] = ord('Z') print("Modified data:", data) # Check the type print(type(view)) |
Output:
Original data: bytearray(b'ABC') Memoryview: <memory at 0x7f...> Modified data: bytearray(b'AZC') <class 'memoryview'> |
Note: The memory address in the memoryview output (<memory at 0x7f...>) will vary each time you run the code.
Example:
result = None |
Example:
# Create a dictionary person = {'name': 'Alice', 'age': 30, 'city': 'New York'} # Access values print("Name:", person['name']) # Modify values person['age'] = 31 print("Updated person:", person) # Add new key-value pair person['email'] = 'alice@example.com' print("Extended person:", person) # Iterate over keys and values for key, value in person.items(): print(f"{key}: {value}") # Check the type print(type(person)) |
Output:
Name: Alice Updated person: {'name': 'Alice', 'age': 31, 'city': 'New York'} Extended person: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'} name: Alice age: 31 city: New York email: alice@example.com <class 'dict'> |
You can check the type of a variable using the type() function.
type_variable = type(42) # Returns <class 'int'> |
Python uses dynamic typing, meaning variables can change type during execution.
var = 10 # var is an int var = 'ten' # var is now a str |
You can create your own data types using classes.
class Person: def __init__(self, name): self.name = name |
The types module provides names for built-in types that aren't directly accessible.
import types function_type = types.FunctionType |
Saranya has understood different data types in Python, such as numeric, sequence, dictionary, boolean, and set. She can work with these data types to analyze data and draw meaningful insights. She is familiar with the basic operations of each data type and can use them for her data science projects.
Answer: D. All of the above
Answer: D. List
Answer: C. String
Top Tutorials
Related Articles