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 sets.py 
s1 = {1,2,3}
s2 = {} # empty sets means the intersection is empty too!
s3 = {}

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

Result

$ python sets.py
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])

Reference

BlinkBlank

Knowledge is the seed of wisdom.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.