Data types
Python offers a variety of data types to store and manipulate different kinds of information. Knowing these types and their specific characteristics is crucial for writing effective and efficient Python code. Here’s a breakdown of the essential data types:
Numeric Types:
- int (integer): Represents whole numbers of unlimited length, positive or negative. Examples: 10, -723, 0.
- float (floating-point): Represents floating-point numbers with limited precision (around 15 decimal places). Examples: 3.14159, 9.81, -2.5.
- complex: Represents complex numbers in the form x + yj, where j is the imaginary unit and x and y are real numbers. Examples: 3 + 2j, 1.5 – 4.7j.
Sequence Types:
- list: An ordered, mutable collection of items, allowing duplicates. Items can be of different data types. Examples: [1, “hello”, 3.14], [“apple”, “banana”, “apple”].
- tuple: An ordered, immutable collection of items. Items can be of different data types. Once created, elements cannot be changed. Examples: (1, “hello”, 3.14), (“orange”, “grape”).
- str (string): Represents sequences of characters (text). Strings are immutable. Examples: “Hello, world!”, “42”, ”.
Mapping Type:
dict (dictionary): An unordered collection of key-value pairs. Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any data type. Examples: {“name”: “Alice”, “age”: 30}, {“fruit”: “banana”, “count”: 2}.
Set Types:
- set: An unordered collection of unique items. Items can be of any data type, but must be hashable (meaning they can be used as dictionary keys). Examples: {1, 2, 3, 4}, {“apple”, “banana”}.
- frozenset: An immutable set. Once created, its items cannot be changed. Examples: frozenset({1, 2, 3, 4}), frozenset((“a”, “b”, “c”)).
Boolean Type:
bool: Represents Boolean values: True or False. Used for logical conditions and comparisons. Examples: True, False.
None Type:
None: Represents the absence of a value. Often used as a placeholder or to indicate that a variable has no assigned value. Example: None.
The type() function
The type() function returns the type of the data passed to it.
For example,
type(35) #int
type(25.45) #float
type(“hello”) #str
type(True) #bool
Interview Questions
Q. Explain the fundamental differences between mutable and immutable data types in Python, providing examples of each. How does the immutability of a data type influence its usage in Python programs?
Ans:
Mutable: Mutable objects can be changed after they are created. Examples include lists, dictionaries, and sets. You can add, remove, or modify elements within them.
Immutable: Immutable objects cannot be changed once created. Examples include numbers (int, float, complex), strings, tuples, and frozensets. Any operation that appears to modify them actually creates a new object.
The immutability of a data type influences its usage. Immutable objects are generally safer to use as keys in dictionaries or elements in sets, as their values won’t change unexpectedly. They can also be used to represent constant values that should not be modified.
Q. Discuss the scenarios where you would choose a list over a tuple, and vice-versa. What factors influence your decision when selecting between a set and a list?
Ans:
List vs. Tuple: Use a list when you need an ordered collection of items that you might need to change (add, remove, modify). Use a tuple when you have an ordered collection of items that should remain constant throughout the program.
Set vs. List: Choose a set when you need a collection of unique items, and order doesn’t matter. Sets are also efficient for membership testing (checking if an item exists in the set). Lists are used when you need to maintain the order of items and allow duplicates.
Q. Describe the structure and usage of dictionaries in Python. What are the advantages of using dictionaries compared to other data types? Explain the concept of “hashability” and its relevance to dictionary keys?
Ans:
Structure: Dictionaries store data as key-value pairs. Each key is unique and associated with a corresponding value. Keys must be hashable (i.e., immutable), while values can be of any data type.
Advantages: Dictionaries provide fast lookups based on keys, making them efficient for storing and retrieving data by name or identifier. They are also flexible and can hold values of different types.
Hashability: Hashability means an object can be converted into a unique hash value. This hash value is used to determine the object’s position in a hash table, enabling fast dictionary lookups. Immutable objects like strings, numbers, and tuples are naturally hashable.
Q. What is the purpose of the None type? How does it differ from an empty string or a zero value? Provide examples where None would be used effectively?
Ans:
Purpose of None: The None type represents the absence of a value. It’s different from an empty string (“”) or zero (0), which are actual values. None is often used:
- As a default return value for functions that don’t explicitly return anything.
- To indicate that a variable has not yet been assigned a meaningful value.
- As a placeholder for optional function arguments.
Q. Given the variable price = 25.99, what would be the output of type(price) and why?
Ans: The output of type(price) would be <class ‘float’>. This is because the value 25.99 has a decimal point, indicating it’s a floating-point number, which is represented by the float type in Python.