Python Lists, Nested Lists & List Comprehension
Python Lists, Nested Lists & List Comprehension Interview Questions
What is a list in Python?
A list is an ordered, mutable collection of items. Lists can contain elements of different data types and are defined using square brackets []. Example: my_list = [1, 2, 3, "hello", True].
What is list slicing in Python?
List slicing extracts parts of a list using the syntax list[start:stop:step]. Example: numbers[1:4] gets elements from index 1 to 3. Negative indices count from the end: numbers[-3:] gets last 3 elements.
What are common list methods in Python?
append() - adds element at end
extend() - adds multiple elements
insert() - inserts at specific position
remove() - removes first matching element
pop() - removes and returns element at index
sort() - sorts list in place
reverse() - reverses list in place
extend() - adds multiple elements
insert() - inserts at specific position
remove() - removes first matching element
pop() - removes and returns element at index
sort() - sorts list in place
reverse() - reverses list in place
What is list comprehension in Python?
List comprehension is a concise way to create lists. Syntax: [expression for item in iterable if condition]. Example: squares = [x**2 for x in range(10)] creates list of squares from 0 to 81.
What is a nested list in Python?
A nested list is a list containing other lists as elements. Example: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. Access elements using multiple indices: matrix[0][1] returns 2.
How to flatten a nested list?
Multiple ways:
# Using nested loops
flat_list = []
for sublist in nested_list:
for item in sublist:
flat_list.append(item)
# Using list comprehension
flat_list = [item for sublist in nested_list for item in sublist]
# Using itertools.chain
from itertools import chain
flat_list = list(chain.from_iterable(nested_list))
What is the difference between append() and extend() methods?
append() adds its argument as a single element to the end of a list. extend() iterates over its argument and adds each element. Example: list.append([1,2]) adds list as element, list.extend([1,2]) adds 1 and 2 as separate elements.
How to create a list with list comprehension with if condition?
Syntax: [expression for item in iterable if condition]. Example: even_numbers = [x for x in range(20) if x % 2 == 0] creates list of even numbers from 0 to 18.
What is the difference between sort() and sorted()?
sort() is a list method that sorts the list in place and returns None. sorted() is a built-in function that returns a new sorted list from any iterable, leaving the original unchanged.
How to copy a list in Python?
Shallow copy: new_list = old_list.copy() or new_list = old_list[:]
Deep copy (for nested lists): import copy; new_list = copy.deepcopy(old_list)
Assignment (new_list = old_list) creates a reference, not a copy.
Deep copy (for nested lists): import copy; new_list = copy.deepcopy(old_list)
Assignment (new_list = old_list) creates a reference, not a copy.
How to use list comprehension with if-else conditions?
Syntax: [expression1 if condition else expression2 for item in iterable]. Example: result = ["even" if x%2==0 else "odd" for x in range(5)] creates ['even', 'odd', 'even', 'odd', 'even'].
What is the difference between remove() and pop() methods?
remove() removes the first matching value and returns None. pop() removes and returns the element at a specific index (default last). remove() takes a value, pop() takes an index.
How to create a 2D list (matrix) using list comprehension?
Example: matrix = [[i+j for j in range(3)] for i in range(3)] creates:
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
This creates a 3x3 matrix with values based on row and column indices.
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
This creates a 3x3 matrix with values based on row and column indices.
What is the time complexity of list operations in Python?
append(): O(1)
insert(): O(n)
pop() (end): O(1)
pop() (middle): O(n)
remove(): O(n)
index(): O(n)
in operator: O(n)
insert(): O(n)
pop() (end): O(1)
pop() (middle): O(n)
remove(): O(n)
index(): O(n)
in operator: O(n)
How to transpose a matrix (2D list) using list comprehension?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
# Result: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Or using zip: transpose = list(map(list, zip(*matrix)))
What is list unpacking in Python?
List unpacking assigns elements of a list to multiple variables. Example: a, b, c = [1, 2, 3] assigns 1 to a, 2 to b, 3 to c. Use * to capture remaining elements: first, *middle, last = [1, 2, 3, 4, 5].
How to find common elements between two lists?
# Using list comprehension
common = [x for x in list1 if x in list2]
# Using sets (faster for large lists)
common = list(set(list1) & set(list2))
Set method is O(1) average for lookups vs O(n) for list method.
What is the difference between list and array?
Lists are built-in Python data structures that can hold heterogeneous data types. Arrays (from array module or NumPy) are more memory efficient for homogeneous data types and support mathematical operations. Lists are more flexible, arrays are faster for numerical computations.
How to remove duplicates from a list?
# Preserving order (Python 3.7+)
from collections import OrderedDict
unique_list = list(OrderedDict.fromkeys(my_list))
# Using set (doesn't preserve order)
unique_list = list(set(my_list))
# Using list comprehension (preserves order)
unique_list = []
[unique_list.append(x) for x in my_list if x not in unique_list]
How to use nested list comprehension?
Nested list comprehension creates lists of lists. Syntax: [[expression for inner_item in inner_iterable] for outer_item in outer_iterable]. Example: matrix = [[0 for _ in range(3)] for _ in range(3)] creates 3x3 matrix of zeros.
Why is row = [[]] * 3 a trap?
All three rows reference the same inner list—mutating one mutates all. Build with [[] for _ in range(3)].
What does lst.sort() return?
None—sort is in-place. Use sorted(lst) if you need a new list.
a += [1, 2] vs a = a + [1, 2] when a is a list?
+= usually mutates in place (extend); + builds a new list—aliasing behaves differently if another variable references a.
min([])—what happens?
ValueError—guard empty lists or provide default= in Python 3.4+.
Why bisect requires sorted input?
Binary search assumes order—wrong order yields meaningless insertion indices.
lst.pop(0) vs deque.popleft()?
Popping index 0 shifts the whole list—O(n). deque left pops are O(1).
[0] * 5 vs [[0]] * 5?
Ints copy by value conceptually; nested mutable inner lists alias—same shared-reference issue.
reversed(lst) gives a list?
Iterator—consume once or wrap in list(); original list unchanged.
lst.index(x) when x missing?
ValueError—unlike find on strings; catch or test membership first.
remove(val) removes how many occurrences?
Only the first match—loop or comprehension if you need all.
Is Python’s list.sort stable?
Yes—equal keys keep relative order—important for multi-pass sorting keys.
Does b = a[:] deep-copy nested lists?
No—shallow slice copies the outer list; inner lists are shared—use copy.deepcopy if needed.
zip(a, b) stops where?
At the shortest iterable—extra items in the longer input are ignored unless using zip_longest.
enumerate(xs, start=1) gotcha?
Indices start at 1 for humans—don’t mix up with zero-based indexing into slices unless intentional.
lst.count(x) complexity?
O(n) scan—membership in huge lists isn’t constant time.
del lst[i:j] behavior?
Removes slice in place—later indices shift immediately.
Why avoid in lists inside tight loops?
Linear scans—convert to set for repeated membership if elements hash.
array.array vs list for numbers?
Compact storage (typecode); fewer methods—great for large homogeneous buffers.
heapq keeps sorted list?
Maintains heap invariant—not fully sorted—use heapq.nlargest or sort when you need total order.
random.shuffle returns?
None—shuffles in place; assign result wrongly loses reference pattern.
lst.insert(k, x) amorts how?
Shifts tail elements—costly near front on large lists.
clear() vs del lst[:]?
Both empty the list—same object identity for lst; choose readability.
Truthiness of empty list?
Falsy—if not lst: is idiomatic.
list.extend(iter) vs looping append?
Extend batches C-side growth better—often faster than many appends from Python loops.
Multi-dimensional comprehension order?
Rightmost for varies fastest—transpose logic mistakes flip rows/columns.
itertools.chain.from_iterable depth?
Flattens one level only—deep nests need recursion or explicit loops.
slice object reuse?
lst[slice(1, None, 2)]—handy for APIs parameterizing start/stop/step.
Why not compare lists with is?
== compares elements; is checks object identity—different lists can compare equal.
lst * 0?
Empty list—useful edge case in dynamic sizing algorithms.
Final: list as stack—operations?
append / pop() last—queues need deque for efficient front pops.
Note: Lists are one of Python's most versatile data structures. List comprehension provides a more readable and efficient way to create and manipulate lists. Understanding list operations, slicing, and comprehension is essential for writing clean, efficient Python code. Lists are mutable, ordered collections that can contain heterogeneous elements, making them suitable for many programming scenarios.