Python tutorials > Core Python Fundamentals > Data Types and Variables > What are fundamental Python data types?

What are fundamental Python data types?

Python is a dynamically-typed language, meaning you don't need to explicitly declare the data type of a variable. Python infers the type based on the value assigned to it. Understanding fundamental data types is crucial for writing efficient and error-free Python code. This tutorial will cover the core data types: integers, floats, strings, booleans, lists, tuples, sets, and dictionaries.

Numeric Types: Integers and Floats

Integers (int): Represent whole numbers, positive or negative, without any decimal point. Examples: -5, 0, 100.

Floats (float): Represent real numbers with a decimal point. They can also represent numbers in scientific notation. Examples: 3.14, -2.5, 1.0e-5.

integer_number = 10
floating_point_number = 3.14

String Type: Textual Data

Strings (str): Represent sequences of characters. They are immutable, meaning you cannot change the characters within a string after it's created. Strings are enclosed in either single quotes (') or double quotes ("). Triple quotes (''' or """) are used for multiline strings.

my_string = "Hello, World!"
another_string = 'Python is fun'

Boolean Type: True or False

Booleans (bool): Represent truth values. They can be either True or False. Booleans are often used in conditional statements and logical operations.

is_true = True
is_false = False

List Type: Ordered and Mutable Collections

Lists (list): Represent ordered collections of items. Lists are mutable, meaning you can change their contents (add, remove, or modify elements) after creation. Lists are defined using square brackets ([]) and elements are separated by commas.

my_list = [1, 2, 3, 'apple', 'banana']
empty_list = []

Tuple Type: Ordered and Immutable Collections

Tuples (tuple): Similar to lists, but they are immutable. Once a tuple is created, its contents cannot be changed. Tuples are defined using parentheses (()) and elements are separated by commas.

my_tuple = (1, 2, 3, 'apple', 'banana')
empty_tuple = ()

Set Type: Unordered and Unique Collections

Sets (set): Represent unordered collections of unique items. Sets are useful for removing duplicates from a collection and performing set operations like union, intersection, and difference. Sets are defined using curly braces ({}) or the set() constructor.

my_set = {1, 2, 3, 4, 5}
set_with_duplicates = {1, 2, 2, 3, 3, 3}
print(set_with_duplicates) # Output: {1, 2, 3}

Dictionary Type: Key-Value Pairs

Dictionaries (dict): Represent collections of key-value pairs. Each key must be unique, and it's used to access its corresponding value. Dictionaries are defined using curly braces ({}) and key-value pairs are separated by colons (:).

my_dictionary = {'name': 'Alice', 'age': 30, 'city': 'New York'}
empty_dictionary = {}

Concepts Behind the Snippets

The key concept is data representation. Each data type is designed to efficiently store and manipulate different kinds of information. Understanding their properties (mutable vs. immutable, ordered vs. unordered, unique vs. non-unique) is vital for selecting the right type for a specific task.

Real-Life Use Case Section

Imagine you're building a student management system. You might use:

  • int to store student IDs.
  • str to store student names and addresses.
  • float to store GPA.
  • bool to indicate whether a student is active.
  • list to store a list of courses a student is enrolled in.
  • tuple to represent a student's date of birth (year, month, day).
  • set to store the unique courses offered by the university.
  • dict to store all information of one student (name, id, courses...)

Best Practices

  • Choose the right data type: Select the data type that best represents the data you're working with. For example, use an integer for counting whole items and a float for representing measurements.
  • Understand mutability: Be aware of whether a data type is mutable or immutable. Modifying a mutable object can have unintended side effects if the object is referenced in multiple places.
  • Use meaningful variable names: Choose variable names that clearly describe the data they hold.
  • Type hinting: Use type hints (introduced in Python 3.5) to improve code readability and help catch type errors early on.

Interview Tip

Be prepared to discuss the differences between mutable and immutable data types, and provide examples of each. Also, be able to explain the use cases for different data structures like lists, tuples, sets, and dictionaries.

When to Use Them

  • Integers: For counting, indexing, and representing whole numbers.
  • Floats: For representing real numbers with decimal points, such as measurements, financial data, and scientific calculations.
  • Strings: For representing text data, such as names, addresses, and descriptions.
  • Booleans: For representing truth values, such as flags, conditions, and switches.
  • Lists: For storing ordered collections of items that may need to be modified.
  • Tuples: For storing ordered collections of items that should not be modified.
  • Sets: For storing unordered collections of unique items, such as unique IDs, tags, or categories.
  • Dictionaries: For storing key-value pairs, such as configurations, mappings, and records.

Memory Footprint

Generally, int and float have relatively small memory footprints. str's memory usage depends on the length of the string. list and dict can consume significant memory, especially with large datasets. tuple typically has a smaller memory footprint than a list due to its immutability, and set's memory consumption depends on the number of unique elements.

Alternatives

  • For numeric computations, consider using the NumPy library, which provides efficient array objects and mathematical functions.
  • For string manipulation, the re module (regular expressions) offers powerful pattern matching capabilities.
  • For more specialized data structures, the collections module provides types like namedtuple, deque, and Counter.

Pros

  • Simplicity: Python's data types are easy to understand and use.
  • Flexibility: Python supports a wide range of data types, allowing you to represent complex data structures.
  • Dynamic Typing: Python's dynamic typing simplifies development by eliminating the need for explicit type declarations.

Cons

  • Dynamic Typing: Can lead to runtime type errors if not careful.
  • Memory Overhead: Python's dynamic nature and object-oriented approach can result in higher memory consumption compared to statically-typed languages.

FAQ

  • What is the difference between a list and a tuple?

    Both lists and tuples are ordered collections, but lists are mutable (changeable) while tuples are immutable (unchangeable). Lists are defined using square brackets [], and tuples are defined using parentheses ().

  • When should I use a set instead of a list?

    Use a set when you need to store a collection of unique items and the order of the items is not important. Sets provide efficient membership testing and set operations.

  • What is the difference between single quotes and double quotes for strings?

    In Python, single quotes and double quotes are generally interchangeable for defining strings. However, you might use one over the other to avoid escaping characters. For example, you can use single quotes if your string contains double quotes and vice versa.