Python / Core Python Fundamentals Interview Questions
What is a Python list and what operations are most commonly used?
A list is Python's built-in ordered, mutable sequence. It can hold items of any type — including other lists — and grows or shrinks dynamically. Lists are backed by a C array that doubles in capacity when it runs out of space, so appending is O(1) amortised.
# Creation items = [10, 'hello', 3.14, True] # Indexing (zero-based, negative counts from end) print(items[0]) # 10 print(items[-1]) # True # Slicing [start:stop:step] print(items[1:3]) # ['hello', 3.14] # Mutating items.append('new') # add to end items.insert(1, 99) # insert at index 1 items.remove('hello') # remove first occurrence popped = items.pop() # remove and return last element items.sort() # in-place sort (only works if items are comparable) items.reverse() # in-place reverse # Length and membership print(len(items)) # number of elements print('new' in items) # True / False
List comprehension is the idiomatic way to build a new list from an existing iterable:
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25] evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
Lists are passed by reference — assigning a list to a second variable gives you a second name for the same object. Use list.copy() or list[:] for a shallow copy, or copy.deepcopy() when the list contains nested mutable objects.
More Related questions...