List Comprehensions

One particularly nifty feature of the Python language are list comprehensions. List comprehensions provide a really concise way of constructing lists. 

One, perfectly acceptable way to construct a new list in Python would be as follows:

x = range(10)
myList = [] # this is an empty list

for i in x:

List comprehensions give us a way to achieve the same result with far few lines of code, like so:

x = range(10)
myList = [i for i in x]

The use of a list comprehension in this simple example removes the need to (a) create an empty list object and (b) construct a for loop block to iterate over the object whose items we are a seeking to add to the empty list.

Write contents of list to column in Pandas dataframe

Let's say we have the following list:

myList = ['Wolf', 'Fox', 'Shark']

To write the contents of myList to a column in a Pandas dataframe, we'd do the following:

import pandas as pd # Bring in Pandas

myList = ['Wolf', 'Fox', 'Shark'] 

# Create empty dataframe with a column named 'Animals'

df = pd.DataFrame(columns=['Animals'])

# Write myList to the Animals column

df['Animals'] = myList

Uniqify a Python List

I came across this really cool blog post outlining various fast ways to remove duplicate values from a Python list. 

Here's the fastest order-preserving example:

def f12(seq):
    return list(dict.fromkeys(seq))

my_list = [1,2,2,2,3,4,5,6,6,6,6]

print (f12(my_list))


[1, 2, 3, 4, 5, 6]

This really quick solution appears to have been identified by a chap called Raymond Hettinger, so credit where it's due!