Python Data Types Interview Questions and Answers
1.What are the basic built-in data types of Python. Specify which of them are mutable and which ones are immutable.
The completely different built-in data types in Python form a large number to work with all different forms of data.
Some of the common data types include:
• Integers (int): These are whole numbers such as 1, 50, or -200. They are immutable.
• Floating point numbers (float) will have decimals like 3.14 or -0.001. These are also immutable.
• Strings (str): A sequence of characters will be considered a string. For example, "hello" or "Python".
These are immutable as well.
• Booleans (bool): A Boolean can be True or False, used in logical operations. An immutable type.
• List - An ordered mutable collection of items such as [1, 2, 3]. Mutable.
• Tuple - Ordered immutable collection such as (1, 2, 3). Immutable.
• Dictionary - Key value pairs such as {"name": "Alice", "age": 30}. Mutable.
• Set - Unordered collection of distinct items, like {1, 2, 3}. Mutable.
Types that can be altered after being created are called mutable, whereas immutable types can never be changed after being created. The particular characteristic affects the behavior of the types throughout the entire code, as in the event of a mutable object being changed within some function; all future guesses will persist outside that function.
2.What are the key differences between Python lists and tuples? Provide scenarios for when you would choose each.
Python lists and tuples are primarily distinguishable by their flexibilities and uses:
Lists:
It's like a living container, like a shopping list you can easily add to, remove from or change the order of items in.
They are mutable meaning one can modify the contents after already being created .
Items are wrapped with square bracket [].
Tuples:
Consider them as fixed records- such as the details on your passport once they are set, they generally don't change.
They are immutable so after you create a tuple, you can't alter it. You should then create a new tuple whenever you would like some modifications.
Defined using parentheses ().
When do you use one over the other?
You would typically select a list when:
You have a collection that potentially might grow and shrink: for example, a list of tasks a collection of user inputs or perhaps a sequence of data you are processing.
Order of items matters and you might need to reorder them (sort, reverse).
You need to modify the individual elements within the collection.
Usually, you'd select the tuple when:
You have an unchangeable collection of related items, like coordinates (x,y), RGB color values or days of the week.
You want to make sure that the data can't change to prevent accidental modification. The tuple's immutability becomes that safeguard.
You need to use the collection as a key in a Python dictionary. Dictionaries require their keys to be immutable, so lists can't be used as keys but tuples can (if they contain only immutable elements).
Returning multiple values to a function and wanting to reference them as a single, unchanging unit.
In essence, lists offer flexibility for collections that might evolve, while tuples provide stability and a guarantee that the data within won't be altered.
The choice depends on the specific needs of your program and the nature of the data you're working with.
3.Explain the structure of Python dictionaries and describe common use cases.
A Python dictionary may be imagined like a super handy address book. Instead of remembering where someone is in a list, you remember their name (the key) and you can instantly find their address, phone number, or whatever other info might be linked to that name (the value).
So essentially, a dictionary is a collection of such name-info pairs. Each "name" (key) has a corresponding "info" (value) attached to it. The cool thing is that those "names" must be unique you can't have two entries for the exact same name. But the "info" can be anything you want: a number, a sentence or even another list of things.
Think of it this way:
my_address_book = {
"Alice": "123 Main St",
"Bob": "456 Oak Ave",
"Charlie": "789 Pine Ln"
}
print(my_address_book["Alice"]) # This will show "123 Main St"
You see? You use the name "Alice" (the key) to quickly get her address (the value).
Dictionaries are great when you want to look something up fast with a distinctive label.
For instance, you might use one for storing players' scores in a game (player name being the key, score being the value) or for keeping count of how many times each word in a document appears (the word as key, the count as value). They are all about linking one thing to another as clearly as possible.
4.Briefly, describe sets in Python. What are sets usually characterized by, and what types of common operations can you perform on sets?
A set in Python is nothing but an unordered collection of unique items. Python automatically deletes duplicates in sets means do not allow duplicates.
Example: my_set = {1, 2, 3, 4}
Features:
• Value duplication not allowed.
• Unordered
• Values are not accessed through indexing
Typical operations on sets:
• add() - Include a New Element
• remove() - Take Away a Specified Element
• union() - Merge two sets in a set
• intersection() - Get common items
• difference() - In one but not the other set
Sets are mainly for membership testing (is 5 in a set?), deduplication of lists or for some mathematical-like operations among groups of data.
5.Differentiate between int and float in Python. When is the precision of a float a significant concern?
Fundamentally, numbers are a vital part of any program in Python. There are two types of numbers mostly used, int (integer) and float (floating point). Though at the first glance they seemed similar as both represent numbers, they are actually used in different contexts, each with its own features and behavior.
What is int in Python?
An int stands for integer, it refers to a non decimal whole number. These numbers includes positive, negative or even zero.
Examples:
x= 10
y= -7
z= 0
In Python, size of an integer is not made fixed as in some other languages. You can make very large integer values and Python automatically increases size as required.
What is float in Python?
Float means a floating-point number. These numbers have a decimal point. These are used when more precision is needed-in for money, measurements or scientific calculation examples.
Examples:
a = 3.14
b = -0.005
c = 2.0
Python treats everything that consists of a decimal point even if that decimal is not visible (for instance, in the example of 2.0), as a float.
Key Differences Between int and float
Let's have a quick on the main points that set these two apart:
Decimal Point: The absence of decimal point for int, presence of decimal point for float.
Precision: float can represent very small or very large values with decimal points, but might lose precision after many digits.
Memory and Performance: int operations are usually slightly faster and more precise because they don't deal with fractional parts.
Usage: Use int for counting or indexing. Use float for measurements, currency (with caution), and more precise math.
When is Float Precision a Concern?
While floats are strong they have a small cost—precision errors. Because computers store floating-point numbers in binary, not every decimal value can be exactly represented. This sometimes leads to small rounding errors.
Example:
x= 0.1 + 0.2
print(x) # Output: 0.30000000000000004
This might not matter in average programming, but even small error like this may have a large impact when using it for financial application, science research or engineering tools.
In such circumstances, you may:
Use the decimal module for more accurate decimal arithmetic.
Round the result using round() when displaying or storing values.
Avoid comparison of floats directly (==), use checking if they are "close enough."
6.How are strings handled in Python? Explain indexing and slicing. Are strings mutable?
Strings:Imagine you type a word or a sentence on your computer. In Python, that's called a string. It's just a bunch of letters (or numbers or symbols) all in a row.
Indexing (Looking at One Letter at a Time) :
Think of each letter in your word having a secret number, starting from zero for the very first letter.
For example, in the word "APPLE":
"A" is at number 0
"P" is at number 1
"P" is at number 2
"L" is at number 3
"E" is at number 4
If you want to see a specific letter, you just use its number in square brackets []:
word = "APPLE"
first_letter = word[0] # You'll get "A"
third_letter = word[2] # You'll get "P"
You can even count from the back using minus signs:
last_letter = word[-1] # You'll get "E"
second_last = word[-2] # You'll get "L"
Slicing :
Taking a Piece of the Word
What if you want a part of the word, like "APP"?
You can "slice" it out. You tell Python where to start and where to end (but it stops just before the end) using a colon : in the square brackets:
word = "APPLE"
first_three = word[0:3] # You'll get "APP" (from number 0 up to, but not including, number 3)
from_second_on = word[1:] # You'll get "PPLE" (from number 1 to the end)
up_to_third = word[:3] # You'll get "APP" (from the beginning up to, but not including, number 3)
Mutability:
Strings in Python are immuatable means that once string is created it's contents can not be changed.
Can You Change the Word After You Type It?
Here's a big thing to remember: once you make a word (a string) in Python, you can't go back and change the letters in the original word directly. It's like writing in pen – you can't just erase a letter.
If you want to make a new word that's almost the same but with a change, you have to create a brand new word. For example, to change "APPLE" to "BPPLE", you'd make a new one:
word = "APPLE"
new_word = "B" + word[1:] # You make "BPPLE" by putting "B" in front of "PPLE" from the old word.
So, Python treats words (strings) as fixed. You can easily look at them and take parts of them, but you can't change the original. If you need a change, you just make a new one.