Python Data Types Interview Questions
Last Updated :
26 Aug, 2025
Python’s built-in data structures are among its most powerful features, enabling fast and flexible coding. Interviewers often assess a candidate's ability to use these structures effectively in both theoretical and practical scenarios.
The most important interview questions on Python data structures: List, Tuple, Set, Dictionary and String.
1. How can you concatenate two lists in Python?
We can concatenate two lists in Python using the +operator or the extend() method.
This creates a new list by joining two lists together.
Python
a = [1, 2, 3]
b = [4, 5, 6]
res = a + b
print(res)
- Using the extend() method:
This adds all the elements of the second list to the first list in-place.
Python
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)
2. What is the difference between a Set and Dictionary?
- A Python Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set.
- Syntax: Defined using curly braces {} or the set() function.
s = {1, 2, 3}
- Dictionary in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
- Syntax: Defined using curly braces {} with key-value pairs.
d = {"a": 1, "b": 2, "c": 3}
Python
# Set: Only values, no duplicates allowed
s = {1, 2, 3, 2, 1}
print("Set:", s)
# Dictionary: Key-value pairs
d = {"a": 1, "b": 2, "c": 3}
print("Dictionary:", d)
# Accessing elements
# Sets: Only iteration
for i in s:
print("Set item:", i)
# Dictionary: Access via keys
print("Value of key 'b':", d["b"])
OutputSet: {1, 2, 3}
Dictionary: {'a': 1, 'b': 2, 'c': 3}
Set item: 1
Set item: 2
Set item: 3
Value of key 'b': 2
3. What are Built-in data types in Python?
The following are the standard or built-in data types in Python:
- Numeric: The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a floating number, a Boolean, or even a complex number.
- Sequence Type: The sequence Data Type in Python is the ordered collection of similar or different data types. There are several sequence types in Python:
- Python String
- Python List
- Python Tuple
- Python range
- Mapping Types: In Python, hashable data can be mapped to random objects using a mapping object. There is currently only one common mapping type, the dictionary and mapping objects are mutable.
Python Dictionary
- Set Types: In Python, a Set is an unordered collection of data types that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
4. What is the difference between a Mutable datatype and an Immutable data type?
- Mutable data types can be edited i.e., they can change at runtime. Eg: List, Dictionary, etc.
- Immutable data types can not be edited i.e., they can not change at runtime. Eg: String, Tuple, etc.
Python
# Mutable
a = [1, 2, 3]
a[0] = 99
print(a)
# Immutable
s1 = "hello"
# my_str[0] = 'H' # Error: strings are immutable
s2 = "H" + s2[1:]
print(s2)
5. How is a dictionary different from a list?
A list is a collection of elements accessed by their numeric index, while a dictionary is a collection of key-value pairs accessed by keys.
- List: Maintains order, allows duplicate values, and is indexed by position.
- Dictionary: Maintains insertion order (since Python 3.7+), requires unique keys, and provides fast lookups based on keys instead of index.
Python
# List: Accessed by index
a = ["apple", "banana", "cherry"]
print(a[1])
# Dictionary: Accessed by key
d = {"Alice": 25, "Bob": 30}
print(d["Bob"])
6. What is the difference between Python Arrays and Lists?
Lists can hold elements of different data types and are more flexible, while arrays (from the array module) can only store elements of the same type, making them more memory-efficient and faster for numerical data. Lists are commonly used for general-purpose collections, whereas arrays are preferred when type consistency and performance matter.
Example:
Python
from array import array
arr = array('i', [1, 2, 3, 4]) # Array of integers
for x in arr:
print(x)
Example:
Python
a = [1, 'hello', 3.14, [1, 2, 3]]
for x in a:
print(x)
Read more about Difference between List and Array in Python
7. Differentiate between List and Tuple?
Feature | List (list ) | Tuple (tuple ) |
---|
Mutability | Mutable (can be changed) | Immutable (cannot be changed) |
Syntax | Square brackets: [1, 2, 3] | Parentheses: (1, 2, 3) |
Use Case | Suitable for dynamic data | Suitable for fixed or constant data |
Hashable | Not hashable (unusable as dict key) | Hashable if elements are immutable |
Code Example:
Python
import sys
a = [1, 2, 3]
b = (1, 2, 3)
print(sys.getsizeof(a)) # More bytes
print(sys.getsizeof(b)) # Fewer bytes
8. Why do tuple and list behave differently when used as dictionary keys?
- In Python, dictionary keys must be immutable and hashable.
- A tuple is immutable (cannot be changed after creation), so it is hashable and can safely be used as a dictionary key.
- A list is mutable (elements can be added, removed, or changed), so it is unhashable and cannot be used as a dictionary key.
Code Example:
Python
# Using tuple as a dictionary key
d = {(1, 2, 3): "Tuple Key"}
print(d[(1, 2, 3)]) # Works fine
# Using list as a dictionary key
try:
d = {[1, 2, 3]: "List Key"} # Error
except TypeError as e:
print("Error:", e)
OutputTuple Key
Error: unhashable type: 'list'
9. Which sorting technique is used by sort() and sorted() functions of python?
Both sort() (for lists) and sorted() (for any iterable) in Python use an algorithm called Timsort.
- Timsort is a hybrid sorting algorithm derived from Merge Sort and Insertion Sort.
- It is highly efficient because it takes advantage of existing order (runs) in the data.
10. Describe Python Strings, their immutability and common operations.
- A string in Python is a sequence of characters enclosed in single (' '), double (" "), or triple quotes (''' ''' or """ """).
- Immutability: Strings are immutable, meaning once created, their contents cannot be changed. Any operation that modifies a string actually creates a new string object.
Immutability:
Once a string is created, its contents cannot be changed. Operations that modify a string return a new string.
Python
s = "abc"
s[0] = "z" # This give TypeError
Common Operations:
- Concatenation:
"Hello" + " World"
→ "Hello World"
- Repetition:
"Hi" * 3
→ "HiHiHi"
- Indexing & Slicing:
"Python"[0] → 'P'
, "Python"[1:4] → 'yth'
- Membership:
"Py" in "Python"
→ True
Built-in Methods:
- .upper() → "hello".upper() → "HELLO"
- .lower() → "HELLO".lower() → "hello"
- .strip() → " hi ".strip() → "hi"
- .replace("a","b") → "data".replace("a","o") → "doto"
- .split() → "a,b,c".split(",") → ['a','b','c']
- .join() → " ".join(['a','b']) → "a b"
Python
print("GFG")
s = "hello world"
# Common Operations
s[0] # 'h' (indexing)
s[0:5] # 'hello' (slicing)
# Built-in Functions
text.upper() # 'HELLO WORLD'
text.split() # ['hello', 'world']
"-".join(["a", "b"]) # 'a-b'
text.replace("world", "Python") # 'hello Python'
text.find("o") # returns index of first 'o'
f-Strings (formatted strings):
Python
name = "Bob"
age = 25
print(f"Name: {name}, Age: {age}") # 'Name: Bob, Age: 25'
11. What happens when you use mutable data types as default arguments in functions?
- Default values in Python are evaluated once at function definition time.
- If you use a mutable object (like a list), it retains state across calls.
Example:
Python
def add_item(item, a=[]):
a.append(item)
return a
print(add_item(1))
print(add_item(2))
Fix:
Python
def add_item(item, a=None):
if a is None:
a = []
a.append(item)
return a
12. Why is list unhashable, but tuple hashable? Can a tuple be unhashable too?
- A list is unhashable because it is mutable, its contents can change (items can be added, removed, or modified). If Python allowed lists as dictionary keys or set elements, their hash value could change after insertion, breaking the integrity of these data structures.
- A tuple is hashable because it is immutable, once created, its elements cannot be modified, so its hash remains constant. This makes it safe to use as a dictionary key or set element.
- However, a tuple can become unhashable if it contains mutable elements like a list or dictionary inside it.
Code Example:
Python
hash((1, 2, 3)) # Works (all immutable)
hash((1, [2, 3])) # Error: unhashable type: 'list'
13. Why is dict key order preserved in modern Python versions?
In modern Python (3.7+ officially, though it appeared as an implementation detail in 3.6), dictionary key order is preserved because:
- Python’s dictionary was reimplemented with a new compact and efficient internal design.
- Instead of a separate hash table and entries array, it now uses a combined table that keeps insertion order naturally.
- This design both saves memory and makes lookups faster while also retaining the order in which keys were inserted.
- Because this turned out to be very useful (especially for things like JSON handling, configs, predictable iteration), it was made a guaranteed language feature starting from Python 3.7.
Code:
Python
d = {'x': 1, 'y': 2, 'z': 3}
print(d) # Ordered as inserted in 3.7+
14. What is the output of "a" * 0 and [] * 3 and why?
- "a" * 0 -> '' (empty string)
- [] * 3 -> [] (empty list)
- Multiplying by zero returns empty container of same type
Code:
Python
print("a" * 0) # ''
print([] * 3) # []
print([1] * 3) # [1, 1, 1]
15. Why does modifying one row in a 2D list affect all rows?
- If you create a 2D list using list multiplication like matrix = [[0]*3]*3, all rows point to the same inner list.
- So when you modify one row, you’re actually modifying that shared object, and the change shows up in every row.
- Fix: Use a list comprehension to create independent inner lists.
Code Example:
Python
a = [[0]*3]*3
a[0][0] = 99
print(a) # All rows' first elements become 99
#Fix
a = [[0]*3 for _ in range(3)]
print(a)
16. Can you sort a dictionary by values? Return it as a new dict?
Yes, a dictionary can be sorted by its values using the sorted() function with a key parameter (key=lambda). Since dictionaries preserve insertion order (Python 3.7+), you can rebuild a new dictionary with sorted items. For
Code:
Python
d = {'a': 3, 'b': 1, 'c': 2}
sorted_dict = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted_dict) # {'b': 1, 'c': 2, 'a': 3}
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice