Python Coding Tips: Set & List

The following code snippets are very helpful during sets and list operations.

Intersection of sets must check for valid case

$ cat 
s1 = {1,2,3}
s2 = {} # empty sets means the intersection is empty too!
s3 = {}

if set(s1) & set(s2):
    print("no intersection")


$ python
no intersection

Sorting a list of tuple on a field

# sort on field 2
data = [("name", 25), ("address", 30)]
sorted_by_second = sorted(data, key=lambda tup: tup[1])


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: