10 Elegant Scripts for Working with List, Arrays, and Tuples in Python

We all need to work with lists, arrays, and tuples when programming and it seems like every time I work with Python I am impressed by someone else’s concise, elegant code for working with lists, arrays, and tuples. When I come across one of these I end up using that tip/trick a few times then get pulled into another project that doesn’t use Python and quickly forget what I learned; consequently, I want to put all of these in one place so I can find them when I need them. Hopefully others will get some value out of this as well.

My apologies for not properly attributing the sources of these script but I just picked them up over time and did not keep track of their sources.

Elegantly reverse a list:

#Create an array containing 0 - 9
items = range(10)
result = list(items[::-1]) 
#[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Skip items in a list:

#Create an array containing 0 - 9
items = range(10)
result = list(items[::2]) #every other starting at index 0
#[0, 2, 4, 6, 8]
result_skip_first = list(items[1::2]) #every other starting at index 1
#[1, 3, 5, 7, 9]

Deleting items from a list:

#Create an array containing 0 - 9
items = list(range(10))
del items[::2]
#[1, 3, 5, 7, 9]

Create a list of tuples from arrays:

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
#[(1, 4), (2, 5), (3, 6)]

Unzipping a “zip” to tuples:

#from above
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
#zipped is [(1, 4), (2, 5), (3, 6)]

#unzipping
x2, y2 = zip(*zipped)
#x2 is (1, 2, 3)
#y2 is (4, 5, 6)

“Flattening” out nested lists (note that this will only work for one level deep):

nested_lists = [[1,2],[3,4],[5,6],[7,8,9]]
flat_list = sum(nested_lists, [])
#or
flat_list2 = [item for sublist in nested_lists for item in sublist]
#[1, 2, 3, 4, 5, 6, 7, 8, 9]

Removing duplicates:

contains_duplicates = [1, 2, 3, 1, 2, 9, 9, 5, 6, 7, 8])
de_duped = list(set(contains_duplicates))
#[1, 2, 3, 5, 6, 7, 8, 9]

Perform a “diff” between two lists/sets:

items1 = [1,2,3,4,5]
items2 = [3,4,5,6,7]
result = list(set(items1).symmetric_difference(items2))
#[1, 2, 6, 7]

Intersection of two lists/sets:

items1 = [1,2,3,4,5]
items2 = [3,4,5,6,7]
result = list(set(items1) & set(items2))
#[3, 4, 5]

Chunking items in a list/array into tuples:

items = range(1,10)
chunk_size = 3
chunks = list(zip(*[iter(items)]*3))7}
#[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *