Most Common Built-in Data Types in Python

Most Common Built-in Data Types in Python

Data types are fundamental to any programming language. They define the type of data the language allows you to store and manipulate within a program. There are several built-in data types in Python. Understanding these and applying them effectively is important, as choosing the right type for your data leads to more efficient and bug-free programs. This blog will outline Python’s most common built-in data types, starting with a description and example of each. Numbers There are two data types for numbers in Python: integer and floating point. An integer is a number without a decimal, for example, 42. A floating point is a number with a decimal, like 3.141592653589793. In both cases, the number is exactly what you see. Strings are text enclosed in quotes. Single quotes define the start and end of the string: ‘this is normally done’. However, double quotes can be used: “This can also be done”. The quotation mark doesn’t become part of the string in both cases.

Numeric Data Types in Python

Integers (int)

Integers in Python are whole numbers without a fractional part, e.g., int in Python, so you can have positive, negative, or zero.

Definition and Characteristics:

Integers are immutable, meaning their value cannot be changed after creation.

Python supports arbitrarily large integers, limited only by the available memory.

Examples of Usage:

Python

age = 25

year = 2024

balance = -1500

Floating-Point Numbers (float)

Float numbers, also known as real numbers, are represented in the language by the float keyword followed by a decimal point. This allows for precise real-number calculations up to immense numbers or as small as the size of a single electron.

Definition and Characteristics:

Floats are also immutable.

They have a fixed precision, which can sometimes lead to rounding errors.

Examples of Usage:

Python

temperature = 36.6

price = 19.99

distance = -1234.56

Complex Numbers (complex)

Complex numbers, also called complex numbers, consist of real and imaginary parts. In Python, they are represented as a + bj, where a is the real part and b is the imaginary part.

Definition and Characteristics:

Useful in scientific and engineering applications.

The imaginary part is denoted by j.

Examples of Usage:

Python

z1 = 3 + 4j

z2 = 2 – 3.5j

result = z1 + z2 # (5 – 0.5j)

Sequence Data Types

Strings (str)

Strings – denoted with the letter str and enclosed in single, double or triple quotes – store and manipulate text.

Definition and Characteristics:

Strings are immutable.

They support various methods for manipulation and formatting.

Examples of Usage:

Python

name = “Alice”

greeting = ‘Hello, world!’

Multiline =” “” This is a

multiline string.”””

Common String Operations:

Python

# Concatenation

full_name = “John” + ” ” + “Doe”

# Repetition

laugh = “Ha” * 3 # “HaHaHa”

# Slicing

first_letter = name[0] # ‘A’

substring = greeting[7:12] # ‘world’

# Methods

upper_name = name.upper() # ‘ALICE’

lower_greeting = greeting.lower() # ‘hello, world!’

Lists (list)

A list (list) is an ordered collection of items that can contain any type of data. Lists are mutable: their elements can be changed.

Definition and Characteristics:

Lists are created using square brackets [].

They allow duplicate elements and maintain the order of insertion.

Examples of Usage:

Python

fruits = [“apple”, “banana”, “cherry”]

numbers = [1, 2, 3, 4, 5]

mixed = [1, “apple”, 3.14, True]

Common List Operations:

Python

# Accessing elements

first_fruit = fruits[0] # ‘apple’

# Modifying elements

numbers[2] = 10 # [1, 2, 10, 4, 5]

# Adding elements

Fruits. append(“orange”) # [“apple”, “banana”, “cherry”, “orange”]

# Removing elements

Fruits. remove(“banana”) # [“apple”, “cherry”, “orange”]

# Slicing

sublist = numbers[1:4] # [2, 10, 4]

Tuples (tuple)

Tuples are like lists but are immutable, meaning that once created, the elements of a tuple can’t be changed. Their type is called a tuple.

Definition and Characteristics:

Tuples are created using parentheses ().

They are often used to store related pieces of data.

Examples of Usage:

Python

coordinates = (10.0, 20.0)

person = (“Alice”, 30, “Engineer”)

single_element_tuple = (42,)

Differences Between Lists and Tuples:

Lists are mutable, while tuples are immutable.

Tuples can be used as keys in dictionaries, while lists cannot.

Mapping Type

Dictionaries (dict)

Dictionaries are dicts (short for dictionaries), which are containers of key-value pairs. Dicts are unordered, mutable, and indexed by unique keys.

Definition and Characteristics:

Dictionaries are created using curly braces {}.

Keys must be immutable types (e.g., strings, numbers, tuples).

Examples of Usage:

Python

student = {“name”: “Alice”, “age”: 21, “major”: “Computer Science”}

phone_book = {“John”: “555-1234”, “Jane”: “555-5678”}

Common Dictionary Operations:

Python

# Accessing values

student_name = student[“name”] # ‘Alice’

# Modifying values

student[“age”] = 22

# Adding key-value pairs

student[“graduation_year”] = 2024

# Removing key-value pairs

del student[“major”]

# Methods

keys = student.keys() # dict_keys([‘name’, ‘age’, ‘graduation_year’])

values = student.values() # dict_values([‘Alice’, 22, 2024])

Items = student.items() # dict_items([(‘name’, ‘Alice’), (‘age’, 22), (‘graduation_year’, 2024)])

Set Types

Sets (set)

Sets (written set) are unordered collections of unique elements. They are useful for storing items where duplicates are forbidden and for performing operations such as union, intersection, and difference on sets.

Definition and Characteristics:

Sets are mutable, meaning you can add or remove elements.

Elements in a set must be immutable (e.g., strings, numbers, tuples).

Examples of Usage:

Python

fruits = {“apple”, “banana”, “cherry”}

numbers = {1, 2, 3, 4, 5}

Common Set Operations:

Python

# Adding elements

Fruits. add(“orange”) # {“apple”, “banana”, “cherry”, “orange”}

# Removing elements

Fruits. remove(“banana”) # {“apple”, “cherry”, “orange”}

# Union of sets

A = {1, 2, 3}

B = {3, 4, 5}

union_set = A | B # {1, 2, 3, 4, 5}

# Intersection of sets

intersection_set = A & B # {3}

# Difference of sets

difference_set = A – B # {1, 2}

# Checking membership

is_in_set = “apple” in fruits # True

Frozen Sets (frozenset)

A ‘frozen set’ is an immutable version of a set:

Once you create one, it’s frozen in time.

You can’t add or remove elements. it’s

It’s hashable (why was that important again?) and can be used as a key in a dictionary or an element in a set.

Definition and Characteristics:

Frozen sets are immutable.

Useful in situations where a set needs to be constant and hashable.

Examples of Usage:

Python

immutable_fruits = frozen set({“apple”, “banana”, “cherry”})

Differences Between Sets and Frozen Sets:

Sets are mutable, while frozen sets are immutable.

Frozen sets can be used as keys to dictionaries (or as elements of other sets), while mutable ones can’t.

Boolean Type

Booleans (bool)

Booleans (denoted by the type bool) represent the choice of exactly one of two values: True or False. They are used in conditional statements and logical operations.

Definition and Characteristics:

Booleans are immutable.

They are the result of comparison and logical operations.

Examples of Usage:

Python

is_active = True

is_logged_in = False

# Comparison operations

is_greater = 5 > 3 # True

is_equal = 10 == 10 # True

# Logical operations

and_operation = True and False # False

or_operation = True or False # True

not_operation = not True # False

Truthiness and Falsiness in Python: 

Some values are ‘truthy’ and some are ‘falsy’ in Python. Truthy and falsy values are the sole values that evaluate True or False in a Boolean context.

Truthy values: 

Non-zero numbers, non-empty strings, lists, tuples, sets, dictionaries, etc.

False values: 

0, None, empty strings (“), empty lists ([]), empty tuples (()), empty sets (set()), empty dictionaries ({}).

Examples:

Python

if 1: # Truthy

    print(“This is True”)

if” “: # Falsy

    print(“This is False”)

None Type

None (NoneType)

One is a magic value in Python that represents the absence of a value or null value, symbolised by the keyword None. It is used to initialise variables and signal the termination of a list in a recursive algorithm.

Definition and Characteristics:

None is immutable.

It is the only value of the NoneType.

Examples of Usage:

Python

# Initialising variables

result = None

# Function with no return value

def greet(name):

    print(f”Hello, {name}”)

greeting = greet(“Alice”) # greeting is None

# Default parameter value

def add(a, b=None):

    If b is None:

        b = 0

    return a + b

total = add(5) # total is 5

Importance of None in Python: 

None is crucial for various programming scenarios, including:

Initialising variables when the value is unknown.

Indicating the absence of a value.

Serving as a default function argument.

Checking for null values in data processing.

Conclusion

The most commonly used in-built data types in Python are numeric, sequence, mapping, set, booleans, and None. The choice of data type depends on both the application of the code and its efficiency. When I first learned to code, I was taught how to create the simplest variables, and then I gradually built more complex and efficient code. Practice makes perfect, as the saying goes.