Skip to content

Instantly share code, notes, and snippets.

@mortoray
Last active March 7, 2019 20:32
Show Gist options
  • Save mortoray/a03dc5b35773a262d51dbd875b6b75cc to your computer and use it in GitHub Desktop.
Save mortoray/a03dc5b35773a262d51dbd875b6b75cc to your computer and use it in GitHub Desktop.

Basics

# 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
mylist[2]

# 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
try:
	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:
	mylist.remove(item)
	
# with error handling
try:
	mylist.remove( item )
except ValueError:
	pass
	

# 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
mylist.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
mylist.clear()

# 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
mylist[1:3]

More Iteration

# Backward
for item in reversed(mylist):
	print(item)
	
# 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 ):
	print(item)
	
# Skipping elements
# step from element 1 to 6 (exclusive) by 2
for item in itertools.islice( mylist, 1, 6, 2 ):
	print(item)

Creation

# 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) )

Advanced

# 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:
	try:
		n = next(myiter)
		print(n)
	except StopIteration:
		break

# Multiple iterators at the same time
itera = iter(lista)
iterb = iter(listb)
while True:
	try:
		a = next(itera)
		b = next(iterb)
		print(a,b)
	except StopIteration:
		break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment