Bytes

Data Types in Python (With Examples)

Last Updated: 20th October, 2024

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.

Data Types in Python-min.png

What are Data Types?

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.

Different Data Types in Python

Python is a high-level, object-oriented programming language that provides a wide range of data types to aid in developing numerous applications.

List of Python Data Types

  • Numeric Data Types
  • Sequence Data Types
  • Mapping Data Types
  • Dictionaries in Python
  • Booleans in Python
  • Binary Types
  • Sets in Python
  • None Type
CategoryData TypeDescription
Numeric TypesintIntegers of unlimited size.
 floatFloating-point numbers (decimal numbers).
 complexComplex numbers in the form a + bj.
Sequence TypeslistMutable sequences, typically used to store collections.
 strImmutable sequences of Unicode characters (strings).
 tupleImmutable sequences, used to store collections.
 rangeImmutable sequences of numbers, commonly used for looping.
Mapping TypedictMutable mappings of keys to values (dictionaries).
Set TypessetUnordered collections of unique elements (mutable).
 frozensetImmutable versions of sets.
Boolean TypeboolBoolean values True or False.
Binary TypesbytesImmutable sequences of bytes.
 bytearrayMutable sequences of bytes.
 memoryviewMemory views of binary data without copying it.
None TypeNoneTypeRepresents the absence of a value (None).

Understand the Data Types in Python with Examples

1. Numeric Data types

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:

  1. integers: whole numbers without decimals, positive or negative, of unlimited length
  2. floating point numbers: numbers with decimals, positive or negative, of limited length
  3. complex numbers: combinations of real and imaginary numbers, like a + bj

int (Integer)

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'>

float (Floating-Point Number)

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'>

complex (Complex Number)

Example:

# Create complex numbers
complex_num1 = 23j
complex_num2 = 54j

# 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'>

2. Sequence Data Types in Python

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.

  1. Strings: Strings are sequences of characters enclosed in single or double quotes.
  2. Lists: Lists are ordered lines of values enclosed in square brackets. They can include any data type.
  3. Tuples: Tuples are immutable, ordered sequences of values defined using parentheses.

str (String)

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'>

List

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'>

Tuple

Example:

# Create a tuple
coordinates = (10.020.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'>

Range

  • An immutable sequence of numbers, commonly used for looping a specific number of times in for-loops.
  • The range() function generates a sequence of numbers, which can be iterated over. It is memory-efficient because it generates numbers on the fly.

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
forin range(38):
    print("Number:", i)

# Check the type
print(type(numbers))

Output:

Number list: [01234]
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
<class 'range'>

3. Dictionaries in Python

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...

4. Booleans in Data Types in Python

In Python, booleans represent either True or False values. They are crucial for controlling program flow with conditional statements like if and else.

Bool

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 = 105
print("10 > 5:", comparison)

# Check the type
print(type(is_active))

Output:

Result: True
105True
<class 'bool'>

5. Sets in Python

  • Sets in Python are unordered collections of unique elements.  They are mutable and useful for storing and manipulating unique, unordered data. 
  • Sets enable set operations like union, intersection, difference, and symmetric difference. They are useful in mathematics and for removing duplicates from sequences. 
  • Sets are mutable, meaning they can be changed. However, they remain unordered and unindexed.

Set

Example:

# Create a set
unique_numbers = {12321}
print("Unique numbers:", unique_numbers)

# Add elements
unique_numbers.add(4)
print("After adding 4:", unique_numbers)

# Set operations
set_a = {123}
set_b = {345}
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: {123}
After adding 4: {1234}
Union: {12345}
Intersection: {3}
<class 'set'>

Frozenset

  • An immutable version of a set.
  • Once a frozenset is created, you cannot change its elements. Useful when you need a constant set of unique elements.

Example:

# Create a frozenset
frozen_set = frozenset([12321])
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 = {234}
union_frozen = frozen_set.union(set_c)
print("Union with set:", union_frozen)

# Check the type
print(type(frozen_set))

Output:

Frozen set: frozenset({123})
Error: 'frozenset' object has no attribute 'add'
Union with set: frozenset({1234})
<class 'frozenset'>

6. Binary Types

bytes:

  • An immutable sequence of bytes (integers in the range 0 ≤ x < 256).
  • Used for binary data, such as files or network resources. Bytes literals are prefixed with b.

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
forin 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'>

bytearray:

  • A mutable sequence of bytes.
  • Similar to bytes, but mutable. Useful when you need to modify binary data.

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'>

memoryview:

  • A memory-efficient view of another binary object’s data without copying it.
  • Allows you to access the buffer protocol of an object. Useful for large data manipulation.

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.

7. None Type

  • The type of the None object, which represents the absence of a value.
  • None is often used to signify 'no value' or 'empty' and is the default return value of functions that do not explicitly return anything.

Example:

result = None

8. Mapping Type

dict (Dictionary)

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'>

Additional Notes on Data Types in Python

Immutability vs. Mutability:

  • Immutable types cannot be changed after creation (e.g., str, tuple, frozenset, bytes).
  • Mutable types can be changed (e.g., list, dict, set, bytearray).

Type Checking:

You can check the type of a variable using the type() function.

type_variable = type(42# Returns <class 'int'>

Dynamic Typing:

Python uses dynamic typing, meaning variables can change type during execution.

var = 10      # var is an int
var = 'ten'   # var is now a str

Custom Data Types:

You can create your own data types using classes.

class Person:
    def __init__(self, name):
        self.name = name

The types Module:

The types module provides names for built-in types that aren't directly accessible.

import types
function_type = types.FunctionType

Conclusion

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.

Key Takeaways

  1. Python has various built-in data types, including integers, floats, strings, booleans, lists, tuples, dictionaries, and sets.
  2. Each data type has a specific purpose and should be used for the appropriate task.
  3. Integers represent whole numbers. Floats represent real numbers. Strings represent text. Booleans represent truth values. Lists represent collections of values. Tuples represent immutable collections of values. Dictionaries define key-value pairs. Sets represent collections of unique values.
  4. Type conversion can convert one data type into another.
  5. When working with data, remember to consider the data types used and ensure they suit the task.

Quiz

  1. Which of the following is a data type in Python?
    1. String 
    2. Integer 
    3. Float 
    4. All of the above

Answer: D. All of the above

  1. What data type would you use to store a list of values?
    1. Integer 
    2. Float 
    3. String
    4. List

Answer: D. List

  1. What data type would you use to store a single character?  
    1. Integer 
    2. Float 
    3. String 
    4. Boolean

Answer: C. String

Module 4: Data Structures in PythonData Types in Python (With Examples)

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter