Lists in Python - Interview Questions and Answers

A list in Python is a collection of elements that can contain items of different data types. It is dynamic (resizable) and supports various operations. Unlike arrays (e.g., in C), lists can store mixed data types and don't require predefined sizes.

my_list = [1, 2, 3, "hello", 5.5]  # Using square brackets
empty_list = list()  # Using the list() constructor

 

  • Indexing: my_list[0]
  • Negative indexing: my_list[-1]
  • Slicing: my_list[1:3]

Use len():

len(my_list)

 

  • append(x): Adds x as a single element.
  • extend(iterable): Adds elements from an iterable to the list.
lst = [1, 2]
lst.append(3)  # [1, 2, 3]
lst.extend([4, 5])  # [1, 2, 3, 4, 5]

 

  • remove(value): Removes the first occurrence of value.
  • pop(index): Removes and returns an element at index.
  • del list[index]: Deletes an element by index.

Slicing extracts a portion of a list. Syntax: list[start:end:step].

lst = [1, 2, 3, 4]
print(lst[1:3])  # [2, 3]

 

lst.reverse()  # In-place reversal
reversed_list = lst[::-1]  # New reversed list

 

for item in lst:
    print(item)

 

if element in lst:
    print("Found")

 

combined = list1 + list2

 

List comprehensions are concise and more efficient for creating lists.

squared = [x**2 for x in range(5)]

 

shallow_copy = my_list.copy()
deep_copy = copy.deepcopy(my_list)  # For nested lists

 

lst.sort()  # In-place
sorted_list = sorted(lst)  # Returns a new list

 

Mutable objects (like lists) can be changed after creation, whereas immutable objects (like tuples) cannot.

Raises IndexError.

unique = list(set(lst))

 

count = lst.count(element)

 

index = lst.index(element)

 

Negative indices count from the end. -1 refers to the last element.

  • append: O(1)
  • pop: O(1) at the end, O(n) at the beginning.
  • insert: O(n)
  • del: O(n)

flattened = [item for sublist in nested_list for item in sublist]

 

Lists store references to objects, not the objects themselves.

Combine two lists into pairs:

zipped = list(zip(list1, list2))

 

for index, value in enumerate(lst):
    print(index, value)

 

second_largest = sorted(set(lst))[-2]

 

lst = [x for x in lst if x != value]

 

pairs = [(x, y) for x in lst for y in lst if x + y == target]

 

intersection = list(set(list1) & set(list2))

 

union = list(set(list1) | set(list2))

 

difference = list(set(list1) - set(list2))

 

symmetric_diff = list(set(list1) ^ set(list2))

 

Use the heapq.merge() function:

import heapq
merged = list(heapq.merge(sorted_list1, sorted_list2))

 

def chunks(lst, size):
    for i in range(0, len(lst), size):
        yield lst[i:i + size]
chunked = list(chunks(my_list, 3))

 

import random
random.shuffle(my_list)

 

from collections import Counter
most_frequent = Counter(lst).most_common(1)[0]

 

result = " ".join(my_list)

 

matrix = [[1, 2], [3, 4], [5, 6]]
transposed = list(zip(*matrix))

 

data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 22}]
sorted_data = sorted(data, key=lambda x: x['age'])

 

cleaned = [x for x in lst if x]

 

reversed_words = [word[::-1] for word in lst]

 

n = 2
rotated = lst[n:] + lst[:n]

 

is_palindrome = lst == lst[::-1]

 

from itertools import permutations
perms = list(permutations(lst))

 

def flatten(lst):
    for item in lst:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item
flattened = list(flatten(nested_list))

 

  • Use list comprehensions for speed.
  • Avoid redundant copies.
  • Use generators when processing large data.
  • Consider libraries like numpy for numerical data.

List slicing does not create new objects unnecessarily. Use it to access subsets of data without loops.

  • copy(): Shallow copy (only references are copied for nested elements).
  • deepcopy(): Copies all levels of the list.
import copy
deep = copy.deepcopy(lst)
shallow = lst.copy()

 

are_equal = list1 == list2  # Checks order and elements

 

  • numpy: For numerical arrays.
  • pandas: For tabular data.
  • deque (from collections): For faster insertions and deletions.
  • array: For type-restricted arrays
Share   Share