Skip to content
elevatedevco

Data & MLOps

Python data structures (lists, dicts)

Learn Python data structures (lists, dicts): 34 practice questions and answers with an interactive quiz — from the offline AI Learning app.

Intermediate34 questions34 quiz questions

Questions & Answers

Tap a question to reveal its answer. Written for self-study and interview preparation.

What is a Python list, and why is it useful for storing data in AI projects?

A Python list is an ordered collection of items stored in square brackets, like [1, 2, 3]. You can store many values in one variable and access any item using its position (index). In AI projects, lists are great for holding training examples, labels, or predictions all in one place.

What is a Python dictionary, and how is it different from a list?

A Python dictionary stores data as key-value pairs, like {"name": "Alice", "age": 12}. Unlike a list where you find items by their position number, a dictionary lets you look up items by a meaningful label called the key. This makes dictionaries perfect for storing structured information such as a student's profile or a data record.

student = {"name": "Alice", "grade": 8}
If scores = [85, 92, 78, 90], what does scores[0] return?

scores[0] returns 85, the first item in the list. In Python, indexing starts at 0, so the first element is always at index 0, the second at index 1, and so on. This zero-based counting is a convention used across most programming languages.

scores = [85, 92, 78, 90]
print(scores[0])  # prints 85
Which method adds a new item to the end of a Python list?

The .append() method adds a new item to the end of a list. For example, my_list.append(5) adds the number 5 as the last element. This is very useful when collecting data one piece at a time, such as recording new sensor readings or AI model predictions.

data = [1, 2, 3]
data.append(4)
print(data)  # [1, 2, 3, 4]
How do you find the number of items in a Python list?

You use the built-in len() function to count the number of items in a list. For example, len([10, 20, 30]) returns 3. Knowing the length of a list is essential when you need to loop through all training examples or check how many predictions your model has made.

In AI, datasets are often stored as lists of numbers called feature vectors. If features = [height, weight, age], what does features[1] represent?

features[1] represents weight, the item at index 1 (the second position). Remember Python lists use zero-based indexing, so index 0 is height, index 1 is weight, and index 2 is age. This ordered structure is crucial because a machine learning model relies on each value always being at the same position.

features = [170, 65, 14]  # height, weight, age
print(features[1])  # 65 (weight)
How do you access the value associated with a key in a Python dictionary?

You access a dictionary value by placing the key inside square brackets after the dictionary name, like my_dict["key"]. For example, if animal = {"type": "cat", "legs": 4}, then animal["legs"] returns 4. This is how AI systems quickly retrieve stored information without scanning through all entries.

animal = {"type": "cat", "legs": 4}
print(animal["legs"])  # 4
What does the following code print? labels = ["cat", "dog", "cat", "fish", "dog", "dog"] counts = {} for label in labels: if label in counts: counts[label] += 1 else: counts[label] = 1 print(counts)

The code prints {'cat': 2, 'dog': 3, 'fish': 1}. It loops through the list of labels and uses a dictionary to count how many times each label appears. This technique — called frequency counting — is commonly used in AI to understand the distribution of classes in a training dataset.

labels = ["cat", "dog", "cat", "fish", "dog", "dog"]
counts = {}
for label in labels:
    if label in counts:
        counts[label] += 1
    else:
        counts[label] = 1
print(counts)  # {'cat': 2, 'dog': 3, 'fish': 1}
Which of the following correctly creates a Python dictionary to store a student's test scores by subject?

A valid Python dictionary uses curly braces {} with key-value pairs separated by colons. The correct form is {"math": 90, "science": 85, "english": 78}, where the subject names are string keys and the scores are integer values. Dictionaries make it easy to retrieve a specific subject's score directly by name.

What is list slicing, and how can it be used to split a dataset into training and testing sets?

List slicing lets you extract a portion of a list using the syntax my_list[start:end], which returns items from index start up to but not including end. For example, if data has 100 items, data[:80] gives the first 80 for training and data[80:] gives the last 20 for testing. Splitting data this way ensures the model learns from one portion and is evaluated on fresh, unseen examples.

data = list(range(100))
train = data[:80]
test  = data[80:]
What is a list comprehension, and how does it help preprocess data quickly in AI?

A list comprehension is a compact one-line way to create a new list by applying an expression to each item in an existing list, written as [expression for item in iterable]. For example, [x / 100 for x in scores] divides every score by 100 in a single line. In data science, this technique is used to normalize values, convert units, or filter records without writing lengthy loops.

scores = [50, 70, 90]
normalized = [x / 100 for x in scores]
# [0.5, 0.7, 0.9]
A dataset is stored as a list of dictionaries. What does dataset[1]["label"] return? dataset = [ {"feature": 5.1, "label": "setosa"}, {"feature": 6.3, "label": "versicolor"}, {"feature": 4.9, "label": "setosa"}, ]

dataset[1]["label"] returns "versicolor". First, dataset[1] retrieves the second dictionary in the list (index 1), which is {"feature": 6.3, "label": "versicolor"}. Then ["label"] fetches the value associated with the key "label". This pattern — a list of dicts — is a natural way to represent rows of a dataset in Python.

print(dataset[1]["label"])  # "versicolor"
Why might an AI engineer prefer a Python dictionary over a list when storing word frequencies for a text classification model?

A dictionary lets you look up the frequency of any word instantly using the word as a key, without searching through the entire collection. With a list, you would have to check each entry one by one to find a specific word, which gets very slow as the vocabulary grows. This near-instant lookup in dictionaries is one reason they are the go-to structure for building word frequency tables in natural language processing.

What does the .get() method on a dictionary do, and why is it safer than direct key access with square brackets?

dict.get(key) returns the value for the given key if it exists, or None by default if the key is not found, instead of raising an error. For example, counts.get("elephant", 0) returns 0 if "elephant" is not in the dictionary. In AI pipelines, this prevents crashes when the model encounters an unknown word or category not seen during training.

counts = {"cat": 5, "dog": 3}
print(counts.get("fish", 0))  # 0 — no crash
How can you use Python's zip() function with two lists to create a dictionary mapping feature names to values?

zip() pairs up items from two lists element by element, and wrapping it with dict() turns those pairs into a dictionary. For example, dict(zip(["height", "weight"], [170, 65])) creates {"height": 170, "weight": 65}. This is a clean technique to build labeled data records from separate lists of names and values.

keys = ["height", "weight"]
vals = [170, 65]
record = dict(zip(keys, vals))
# {"height": 170, "weight": 65}
What is the difference between list.sort() and sorted(list) in Python?

list.sort() sorts the list in place, meaning it modifies the original list and returns None. sorted(list) returns a brand-new sorted list and leaves the original unchanged. In data science, keeping the original order intact using sorted() can be important when the position of each data point corresponds to a meaningful record ID or timestamp.

data = [3, 1, 4, 1, 5]
new = sorted(data)  # data unchanged
data.sort()         # data modified in place
In a machine learning pipeline, how could you use a dictionary to perform label encoding — converting text category labels into numbers?

You create a dictionary that maps each unique category name to a unique integer, for example {"cat": 0, "dog": 1, "fish": 2}. You then loop over your list of labels and replace each string with its corresponding number using a list comprehension. This is necessary because most ML algorithms work on numbers, not text, so encoding is an essential preprocessing step.

encoder = {"cat": 0, "dog": 1, "fish": 2}
labels  = ["dog", "cat", "fish"]
encoded = [encoder[l] for l in labels]
# [1, 0, 2]
What is a nested dictionary in Python, and how could it represent a small AI dataset with multiple features per sample?

A nested dictionary is a dictionary where some values are themselves dictionaries, allowing you to represent multi-level structured data. For example, {"s1": {"age": 25, "score": 88}, "s2": {"age": 30, "score": 75}} stores two samples each with its own feature dictionary. In AI, this lets you organise complex data records before converting them to formats used by machine learning libraries.

data = {
    "s1": {"age": 25, "score": 88},
    "s2": {"age": 30, "score": 75},
}
print(data["s1"]["age"])  # 25
You want to build a vocabulary for an NLP model. Given a list of words, how would you create a dictionary mapping each unique word to a unique index number?

You loop through the word list, and each time you encounter a word not yet in the dictionary, you assign it the next available index using the current dictionary length. The result is a vocabulary dict like {"hello": 0, "world": 1, "ai": 2}. This vocabulary is then used to convert sentences into lists of numbers, which is the first step in many natural language processing pipelines.

words = ["hello", "world", "hello", "ai"]
vocab = {}
for w in words:
    if w not in vocab:
        vocab[w] = len(vocab)
# {"hello": 0, "world": 1, "ai": 2}
Which dictionary method lets you loop through all key-value pairs at the same time in a for loop?

The .items() method returns each key-value pair as a tuple, allowing you to unpack both in a for loop using for key, value in my_dict.items(). This is useful in AI when you need to process feature names alongside their values, such as printing a model's prediction confidence for each possible class.

results = {"cat": 0.8, "dog": 0.15, "fish": 0.05}
for label, conf in results.items():
    print(label, conf)
An AI model outputs a list of predicted class probabilities: probs = [0.1, 0.7, 0.2]. How would you find the index of the highest probability using Python?

You use max() to find the highest value, and .index() to find its position in the list. probs.index(max(probs)) returns 1, meaning class index 1 has the highest probability. This operation — selecting the most likely class — is called argmax and is a fundamental step in turning a model's raw probability output into a single predicted label.

probs = [0.1, 0.7, 0.2]
best_class = probs.index(max(probs))
print(best_class)  # 1
What is the difference between copying a list with new = old versus new = old[:] in Python?

new = old does not create a copy — both variables point to the exact same list in memory, so changing one changes the other. new = old[:] creates a shallow copy — a separate list with the same items — so changes to the new list do not affect the original. In data science, accidentally sharing references can corrupt your original training data, which is why knowing this difference matters.

a = [1, 2, 3]
b = a        # same object — not a copy!
c = a[:]     # independent copy
b.append(4)
print(a)  # [1, 2, 3, 4]  — a changed!
print(c)  # [1, 2, 3]     — c unchanged
How can you use a Python dictionary to detect and count duplicate items in a list, and why is this useful in data cleaning?

You iterate through the list and use a dictionary to count how many times each item appears. Any key whose count is greater than 1 is a duplicate. Removing or flagging duplicates is important in data cleaning because repeated identical training examples can bias a machine learning model toward those patterns.

data = [3, 1, 4, 1, 5, 3]
counts = {}
for x in data:
    counts[x] = counts.get(x, 0) + 1
dupes = [k for k, v in counts.items() if v > 1]
# dupes = [3, 1]
What does the following one-hot encoding code produce, and why is one-hot encoding used in AI? classes = ["cat", "dog", "fish"] one_hot = {c: [1 if c == cls else 0 for cls in classes] for c in classes}

The code produces {"cat": [1, 0, 0], "dog": [0, 1, 0], "fish": [0, 0, 1]}. Each class gets a list where only its own position is 1 and all others are 0. One-hot encoding is used in AI because it converts categorical labels into numerical vectors without implying any false numerical ordering or relationship between categories.

classes = ["cat", "dog", "fish"]
one_hot = {c: [1 if c == cls else 0 for cls in classes] for c in classes}
# {"cat": [1,0,0], "dog": [0,1,0], "fish": [0,0,1]}
How is a Python dictionary related to the JSON data format, and why does this matter for AI applications?

Python dictionaries and JSON objects share almost identical syntax — both use key-value pairs with curly braces. Python's json module can convert a dictionary to a JSON string with json.dumps() and parse JSON back into a dictionary with json.loads(). This matters in AI because many APIs, datasets, and model responses are transmitted as JSON, and dictionaries make it easy to read, modify, and send that data.

import json
d = {"model": "classifier", "score": 0.9}
text = json.dumps(d)    # dict → JSON string
back = json.loads(text) # JSON string → dict
What happens when you try to access a key in a Python dictionary that does not exist using square bracket notation?

Python raises a KeyError and stops the program. For example, my_dict["missing_key"] will crash if "missing_key" is not in the dictionary. To avoid this, you can use my_dict.get("missing_key") which returns None safely, or my_dict.get("missing_key", default_value) to specify a fallback value.

What does list(my_dict.keys()) return, and how could you use it in a machine learning context?

list(my_dict.keys()) returns a list of all the keys in the dictionary. For example, if my_dict = {"height": 170, "weight": 65}, then list(my_dict.keys()) gives ["height", "weight"]. In ML, this is useful for extracting the feature names from a data record so you know what each column in your dataset represents.

record = {"height": 170, "weight": 65}
feature_names = list(record.keys())
# ["height", "weight"]
Why is looking up a value in a Python dictionary much faster than searching for a value in a Python list, especially as data grows larger?

Dictionaries use a technique called hashing, which converts a key into a memory address directly, allowing near-instant lookup regardless of dictionary size. Lists must be scanned item by item from the beginning, so finding an element takes longer as the list grows. In AI, where vocabularies or label maps can have millions of entries, this speed difference is critical for keeping training and inference fast.

How do you remove a key-value pair from a Python dictionary, and why might you need to do this in a data preprocessing step?

You use the del statement (del my_dict["key"]) or the .pop("key") method to remove a key-value pair; .pop() also returns the removed value. In data preprocessing, you might need to drop irrelevant or sensitive features like a person's name or ID before training an AI model to avoid bias or protect user privacy.

record = {"name": "Alice", "age": 14, "score": 90}
del record["name"]  # remove sensitive field
# {"age": 14, "score": 90}
What will the following code output, and what does this reveal about negative indexing in Python lists? words = ["AI", "learns", "from", "data"] print(words[-1]) print(words[-2])

words[-1] prints "data" and words[-2] prints "from". Negative indices count from the end of the list: -1 is the last item, -2 is second-to-last, and so on. This is handy in AI when you want the most recent item — for example, the last prediction made — without needing to know the exact length of the list.

words = ["AI", "learns", "from", "data"]
print(words[-1])  # "data"
print(words[-2])  # "from"
You are building a simple recommendation system. Ratings are stored as {"Alice": [5, 3, 4], "Bob": [2, 5, 1]}. How would you compute the average rating for each user using a dictionary comprehension?

A dictionary comprehension works like a list comprehension but builds a dictionary. {name: round(sum(r)/len(r), 2) for name, r in ratings.items()} gives {"Alice": 4.0, "Bob": 2.67}. Recommendation systems often compute such averages as a starting point for predicting what a user might enjoy next.

ratings = {"Alice": [5, 3, 4], "Bob": [2, 5, 1]}
avg = {name: round(sum(r)/len(r), 2) for name, r in ratings.items()}
# {"Alice": 4.0, "Bob": 2.67}
In Python, what is the result of "dog" in {"cat": 1, "dog": 2, "fish": 3}, and how is this membership test used in AI?

The expression returns True because the in operator checks whether "dog" is one of the dictionary's keys. This fast membership test is used in AI to check whether a word or category belongs to a known vocabulary before processing it — if it is not found, the system can assign it a special unknown token instead of crashing.

vocab = {"cat": 1, "dog": 2, "fish": 3}
print("dog" in vocab)    # True
print("lion" in vocab)   # False
What is the ethical concern with using imbalanced training data stored in a list, and how might you detect this imbalance using Python dictionaries?

Imbalanced training data can cause AI models to make unfair decisions — for example, if a list of labelled examples contains mostly one group, the model may perform poorly for underrepresented groups. You can detect this by counting the frequency of each label using a dictionary and checking whether the counts are very uneven. Noticing and correcting such imbalances before training is a key responsibility in ethical AI development.

labels = ["group_A"] * 90 + ["group_B"] * 10
counts = {}
for l in labels:
    counts[l] = counts.get(l, 0) + 1
# {"group_A": 90, "group_B": 10}  — very imbalanced!
How does Python's list extend() method differ from append(), and how might you use extend() to combine feature vectors from two data sources?

append() adds a single object as one new element — even if it is a list, it becomes a nested element — while extend() unpacks an iterable and adds each of its items individually to the end. For example, if a = [1, 2] and b = [3, 4], then a.extend(b) gives [1, 2, 3, 4] — a flat combined list. In AI, this is useful for merging feature sets from two different sources into one flat feature vector for a model.

a = [1, 2]
b = [3, 4]
a.append(b)   # [1, 2, [3, 4]]  — nested!
a = [1, 2]
a.extend(b)   # [1, 2, 3, 4]   — flat

Put it into practice with AI Learning

This topic — and hundreds more — comes from our free, offline AI Learning app. Practice Q&A, quizzes and cheat sheets anywhere, no account needed.

  • Free
  • No account
  • Works offline
Coming soon toGoogle Play