Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Data types in Python

Introduction to Data Types in Python

One of the fundamental concepts in Python is the idea of data types, which are essential for understanding how data is stored, manipulated, and used within a program. In Python, data types define the type of value a variable can hold, and they determine what operations can be performed on that value. This introduction will explore the primary data types in Python, including their characteristics, uses, and how to work with them.

1. Numeric Types

Integers (int)

Integers are whole numbers without a decimal point. They can be positive, negative, or zero. In Python, integers are represented by the int class.

Examples:

a = 10
b = -5
c = 0

Operations: You can perform various arithmetic operations with integers, such as addition, subtraction, multiplication, and division.

sum = a + b  # 10 + (-5) = 5
product = a * b  # 10 * (-5) = -50
quotient = a / 2  # 10 / 2 = 5.0 (division always returns a float)

Floating-Point Numbers (float)

Floating-point numbers are numbers with a decimal point. They are used to represent real numbers and are represented by the float class.

Examples:

x = 10.5
y = -3.14
z = 0.0

Operations: Similar to integers, you can perform arithmetic operations with floating-point numbers.

sum = x + y  # 10.5 + (-3.14) = 7.36
product = x * y  # 10.5 * (-3.14) = -32.97

Complex Numbers (complex)

Complex numbers have a real part and an imaginary part and are represented by the complex class. They are written in the form a + bj, where a is the real part and b is the imaginary part.

Examples:

comp = 3 + 4j

Operations: You can perform arithmetic operations with complex numbers as well.

sum = comp + (1 + 2j)  # (3 + 4j) + (1 + 2j) = 4 + 6j
product = comp * (2 - 3j)  # (3 + 4j) * (2 - 3j) = 18 - j

2. Sequence Types

Strings (str)

Strings are sequences of characters enclosed in single, double, or triple quotes. They are represented by the str class.

Examples:

greeting = "Hello, World!"
quote = 'Python is awesome.'
multiline = """This is a
multiline string."""

Operations: You can concatenate strings, repeat them, and access individual characters or slices.

concatenated = greeting + " " + quote  # "Hello, World! Python is awesome."
repeated = greeting * 3  # "Hello, World!Hello, World!Hello, World!"
first_char = greeting[0]  # 'H'
substring = greeting[0:5]  # 'Hello'

Lists (list)

Lists are ordered collections of items, which can be of different types. They are mutable, meaning their contents can be changed after creation.

Examples:

numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]

Operations: You can add, remove, and access elements in a list.

numbers.append(6)  # [1, 2, 3, 4, 5, 6]
numbers.remove(3)  # [1, 2, 4, 5, 6]
first_element = numbers[0]  # 1
slice = numbers[1:3]  # [2, 4]

Tuples (tuple)

Tuples are similar to lists but are immutable, meaning their contents cannot be changed once created.

Examples:

coordinates = (10, 20)
mixed_tuple = (1, "two", 3.0, True)

Operations: You can access elements and perform slicing, but you cannot modify the tuple.

first_element = coordinates[0]  # 10
slice = mixed_tuple[1:3]  # ("two", 3.0)

Ranges (range)

Ranges represent a sequence of numbers and are commonly used for looping a specific number of times.

Examples:

range1 = range(10)  # 0, 1, 2, ..., 9
range2 = range(1, 10, 2)  # 1, 3, 5, 7, 9

Operations: You can iterate over ranges and convert them to lists.

for i in range1:
    print(i)

range_list = list(range2)  # [1, 3, 5, 7, 9]

3. Mapping Types

Dictionaries (dict)

Dictionaries are collections of key-value pairs. Each key must be unique, and keys are used to access corresponding values.

Examples:

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

Operations: You can add, remove, and access key-value pairs in a dictionary.

age = person["age"]  # 30
person["job"] = "Engineer"
del person["city"]

4. Set Types

Sets (set)

Sets are unordered collections of unique elements. They are useful for membership tests and eliminating duplicate entries.

Examples:

fruits = {"apple", "banana", "cherry"}

Operations: You can add, remove, and perform set operations like union, intersection, and difference.

fruits.add("orange")
fruits.remove("banana")
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)  # {1, 2, 3, 4, 5}
intersection_set = set1.intersection(set2)  # {3}

Frozensets (frozenset)

Frozensets are immutable sets. Once created, their contents cannot be modified.

Examples:

immutable_set = frozenset([1, 2, 3, 4])

Operations: You can perform set operations, but you cannot add or remove elements.

intersection_set = immutable_set.intersection({2, 3, 5})  # frozenset({2, 3})

5. Boolean Type (bool)

Booleans represent truth values and are used in conditional statements and logical operations. They have two possible values: True and False.

Examples:

is_true = True
is_false = False

Operations: You can perform logical operations like and, or, and not.

result = is_true and is_false  # False
result = is_true or is_false  # True
result = not is_true  # False

Conclusion

Understanding data types is fundamental to mastering Python programming. Each data type serves a specific purpose and has unique properties and operations. By familiarizing yourself with these data types and their usage, you can write more efficient and effective Python code. Whether you are working with numbers, text, collections, or logical values, Python provides a rich set of data types to meet your needs.