Data Types and Data Structures
Understand primitive data types and structures in Python, including lists, tuples, dictionaries, sets, and custom collection objects.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is the difference between a list and a tuple in Python? - Data Types and Data Structures
| Feature | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutability | Mutable | Immutable |
| Speed | Slower | Faster |
| Memory | More | Less |
| Dict Key | No | Yes |
my_list = [1, 2, 3]
my_list[0] = 99 # Works - mutable
my_tuple = (1, 2, 3)
my_tuple[0] = 99 # TypeError - immutable
# Tuples as dict keys
my_dict = {(1, 2): 'value'} # Works
my_dict[[1, 2]] = 'value' # TypeError
Q2. How do you remove duplicates from a list while preserving order? - Data Types and Data Structures
my_list = [1, 2, 2, 3, 1, 4, 2, 5]
# Method 1: dict.fromkeys() - BEST for Python 3.7+
result = list(dict.fromkeys(my_list))
print(result) # [1, 2, 3, 4, 5]
# Method 2: Loop with set
seen = set()
result = []
for item in my_list:
if item not in seen:
result.append(item)
seen.add(item)
print(result) # [1, 2, 3, 4, 5]
# Method 3: List comprehension with walrus
seen = set()
result = [x for x in my_list if not (x in seen or seen.add(x))]
print(result) # [1, 2, 3, 4, 5]
Q3. What is the difference between a list and a set in Python? - Data Types and Data Structures
| Feature | List | Set |
|---|---|---|
| Ordered | Yes | No |
| Duplicates | Allowed | No |
| Indexing | Yes | No |
| Membership O(n/1) | O(n) | O(1) |
my_list = [1, 2, 3, 2, 1] # [1, 2, 3, 2, 1]
my_set = {1, 2, 3, 2, 1} # {1, 2, 3}
# Set operations
set1 = {1, 2, 3}
set2 = {2, 3, 4}
union = set1 | set2 # {1, 2, 3, 4}
intersection = set1 & set2 # {2, 3}
difference = set1 - set2 # {1}
Q4. What is a dictionary comprehension? - Data Types and Data Structures
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# With condition
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# Inverting dictionary
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
Q5. How does a Python dictionary work internally? - Data Types and Data Structures
# Hash function
hash('key') # Returns hash value
hash('hello') # 8730470218056277053
# O(1) lookup
my_dict = {'name': 'John', 'age': 30}
print(my_dict['name']) # O(1) average time
# Dictionary is hash table
# 1. Hash the key
# 2. Map to index in table
# 3. Retrieve value at index
# Why dicts are fast vs lists
big_dict = {x: x for x in range(1000000)}
big_list = list(range(1000000))
# Dict: O(1)
# List: O(n) - 1000x slower!
# Key must be hashable (immutable)
my_dict[(1, 2)] = 'tuple key' # Works - hashable
try:
my_dict[[1, 2]] = 'list key' # Error - not hashable
except TypeError:
pass
Q6. What is the difference between shallow copy and deep copy? - Data Types and Data Structures
import copy
# Shallow copy - copies only surface level
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0][0] = 999
print(original) # [[999, 2], [3, 4]] - affected!
print(shallow) # [[999, 2], [3, 4]]
# Deep copy - copies all levels
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0][0] = 999
print(original) # [[1, 2], [3, 4]] - NOT affected
print(deep) # [[999, 2], [3, 4]]
# List copy methods
my_list = [1, 2, 3]
shallow_list = my_list.copy() # Shallow copy
shallow_list[0] = 999
print(my_list) # [1, 2, 3] - OK for flat lists
Q7. What is the difference between append() and extend()? - Data Types and Data Structures
my_list = [1, 2]
# append() - adds whole object as single element
my_list.append([3, 4])
print(my_list) # [1, 2, [3, 4]] - nested list!
# extend() - adds each element individually
my_list = [1, 2]
my_list.extend([3, 4])
print(my_list) # [1, 2, 3, 4] - flat list
# Performance
# extend() is faster for adding many items
my_list = [1, 2]
for i in range(10):
my_list.append(i) # 10 operations
my_list = [1, 2]
my_list.extend(range(10)) # 1 operation
Q8. How do you sort a dictionary by its values? - Data Types and Data Structures
my_dict = {'apple': 5, 'banana': 2, 'cherry': 8, 'date': 3}
# Sort by values (ascending)
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict) # {'banana': 2, 'date': 3, 'apple': 5, 'cherry': 8}
# Sort by values (descending)
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict) # {'cherry': 8, 'apple': 5, 'date': 3, 'banana': 2}
# Get as list of tuples
sorted_items = sorted(my_dict.items(), key=lambda x: x[1])
print(sorted_items) # [('banana', 2), ('date', 3), ('apple', 5), ('cherry', 8)]
Q9. What are Python sets used for and how are they different from lists? - Data Types and Data Structures
# Sets store unique elements
my_set = {1, 2, 3, 2, 1} # Duplicates removed
print(my_set) # {1, 2, 3}
# No indexing
# print(my_set[0]) # TypeError
# Unordered
set1 = {3, 1, 2}
set2 = {1, 2, 3}
print(set1 == set2) # True - same elements
# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1 | set2 # {1, 2, 3, 4, 5, 6}
intersection = set1 & set2 # {3, 4}
difference = set1 - set2 # {1, 2}
sym_diff = set1 ^ set2 # {1, 2, 5, 6}
# Fast membership testing - O(1)
large_set = set(range(1000000))
if 500000 in large_set: # Very fast!
print('Found')
Q10. What is the difference between mutable and immutable data types? - Data Types and Data Structures
| Type | Mutable | Immutable |
|---|---|---|
| Examples | list, dict, set | int, str, tuple, frozenset |
| Change in place | Yes | No |
| Dict key | No | Yes |
| Performance | Slower | Faster |
# Mutable - can change in place
my_list = [1, 2, 3]
my_list[0] = 99 # Changes original
my_dict = {'a': 1}
my_dict['a'] = 2 # Changes original
# Immutable - cannot change, create new
my_tuple = (1, 2, 3)
# my_tuple[0] = 99 # TypeError
my_str = 'hello'
# my_str[0] = 'H' # TypeError
new_str = 'H' + my_str[1:] # Create new string
# Immutable types as dict keys
my_dict = {
(1, 2): 'tuple key', # OK
'string': 'value', # OK
42: 'number' # OK
}
# Cannot use mutable types as keys
try:
my_dict[[1, 2]] = 'list key' # TypeError
except TypeError:
print('Lists cannot be keys')
Data Types and Data Structures
Understand primitive data types and structures in Python, including lists, tuples, dictionaries, sets, and custom collection objects.
What is the difference between a list and a tuple in Python? - Data Types and Data Structures
FeatureListTupleSyntax[1, 2, 3](1, 2, 3)MutabilityMutableImmutableSpeedSlowerFasterMemoryMoreLessDict KeyNoYes...
How do you remove duplicates from a list while preserving order? - Data Types and Data Structures
my_list = [1, 2, 2, 3, 1, 4, 2, 5] # Method 1: dict.fromkeys() - BEST for Python 3.7+ result = list(dict.from...
What is the difference between a list and a set in Python? - Data Types and Data Structures
FeatureListSetOrderedYesNoDuplicatesAllowedNoIndexingYesNoMembership O(n/1)O(n)O(1)my_list = [1, 2, 3, 2, 1]...
What is a dictionary comprehension? - Data Types and Data Structures
squares = {x: x**2 for x in range(5)} print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} # With condition even...
How does a Python dictionary work internally? - Data Types and Data Structures
# Hash function hash('key') # Returns hash value hash('hello') # 8730470218056277053 # O(1) lookup my_dict...
What is the difference between shallow copy and deep copy? - Data Types and Data Structures
import copy # Shallow copy - copies only surface level original = [[1, 2], [3, 4]] shallow = copy.copy(origin...
What is the difference between append() and extend()? - Data Types and Data Structures
my_list = [1, 2] # append() - adds whole object as single element my_list.append([3, 4]) print(my_list) # [1...
How do you sort a dictionary by its values? - Data Types and Data Structures
my_dict = {'apple': 5, 'banana': 2, 'cherry': 8, 'date': 3} # Sort by values (ascending) sorted_dict = dict(s...
What are Python sets used for and how are they different from lists? - Data Types and Data Structures
# Sets store unique elements my_set = {1, 2, 3, 2, 1} # Duplicates removed print(my_set) # {1, 2, 3} # No i...
What is the difference between mutable and immutable data types? - Data Types and Data Structures
TypeMutableImmutableExampleslist, dict, setint, str, tuple, frozensetChange in placeYesNoDict keyNoYesPerforma...