Essential Lists Code for a Python Interview

This is a cheat sheet for working with lists in Python. It’s an example of all items list in Essential Interview Code for Lists and Vectors. Knowing this, or having the list handy, will speed you along in coding interviews.


# Create a list
mylist = []

# Add an element to the front or back
mylist.append( "abc" )
mylist.insert(0, "def")

# Pop element off front or back
end = mylist.pop()
start = mylist.pop(0)

# Forward iterate over elements
for item in mylist:
	print( item )
# Get the length of list
len( mylist )

# Test if empty
if not mylist:
	print( "list is empty" )

## Location Based Operations

# Get item at location

# Insert an item at location
mylist.insert( 3, "abc" ) 

# Remove an item from location
del mylist[2]

# Replace/Assign item at location
mylist[1] = "def"

Sorting and searching

# Find an item
if item in mylist:
	index = mylist.index(item)
# Using `index` and error handling
	index = mylist.index( 'abc' )
except ValueError:
	index = None
# Using `next` and filtering
next((x for x in mylist if x == 'ghif'), None)

# Find and remove an item
if item in mylist:
# with error handling
	mylist.remove( item )
except ValueError:

# Find last matching item
# Index of found item, or None
next( (index for index in reversed(range(len(mylist))) if mylist[index] == item), None)

# Alternately, reverse list and use "Find an item", but that copies the list
revlist = mylist[::-1]
if item in revlist:
	index = revlist.index(item)

# Sort by natural order
# in-place sort

# Sort with custom comparator
mylist = [ ('a', 10), ('b', 7), ('c',13), ('d',1) ]
# sort by a key (sub-element
mylist.sort( key = lambda item: item[1] )
# custom comparator
def compare_fn( a, b ):
	return some_cond(a,b)
mylist.sort( key = functools.cmp_to_key( compare_fn ) )

Segment Manipulation

# Split the list at arbitrary location
tail_of_list = mylist[2:]
head_of_list = mylist[:2]

# Multiple splits based on a match
mylist = ['a', 'b', 'c', 'd', 'b', 'e']
[list(y) for x, y in itertools.groupby(mylist, lambda z: z == 'b') if not x]

# Clear the list

# Remove segment
# delete from position 1 up to, but excluding position 3
del mylist[1:3]

# Concatenate lists
mylist + other_list

# Insert list at location
# list slicing replaces the segment of list with another one, here we replace a zero-length slice
mylist[1:1] = other_list

# Get a sublist
# sublist starting at position 1 up to, but excluding, position 3

More Iteration

# Backward
for item in reversed(mylist):
# Partial segment iteration
# using itertools.islice avoids copying the list (which is what would happen if you used a slice)
for item in itertools.islice( mylist, 1, 4 ):
# Skipping elements
# step from element 1 to 6 (exclusive) by 2
for item in itertools.islice( mylist, 1, 6, 2 ):


# Create from a static list of items
mylist = [ 'abc', 'def', 'ghi']

# Create a range of numbers
# a list of numbers from 10..20 (exclusive)
numbers = list(range(10,20))

Data Manipulation

# Mapping
[number * 10 for number in numbers]

# Filtering
[number for number in numbers if number % 2 == 0]

# Fold / Reduce
# Summing up numbers using builtin add
functools.reduce( operator.add, numbers )
# Joining string representations of items
functools.reduce( lambda left,right: str(left) + '/' + str(right), mylist )

# Zip
# the zip function produces a list of tuples
zip( lista, listb )
# to alternate items into one list use reduce
functools.reduce( operator.add, zip(lista, listb) )


# Swap elements at two locations
mylist[3], mylist[5] = mylist[5], mylist[3]

# Reserve capacity
# Python lists do not expose capacity

# Replace content in a list
mylist[:] = other_list

# Compare two lists
lista == listb

# Search a sorted list
# bisect_left/bisect_right work with sorted lists,
# find an item ndx using bisect_left, finds the left-most item
ndx = bisect_left(numbers, 4)
if ndx != len(numbers) and numbers[ndx] == 4
	print( "Found at {}".format(ndx) )

# Iterators
# Manually stepping through an iterator
myiter = iter(mylist)
while True:
		n = next(myiter)
	except StopIteration:

# Multiple iterators at the same time
itera = iter(lista)
iterb = iter(listb)
while True:
		a = next(itera)
		b = next(iterb)
	except StopIteration:

Edaqa Mortoray

An avid writer and expert programmer. He’s been on both sides of the interview table countless times and enjoys sharing his experiences.