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


Python Cheatsheet – IV

Enumerate a list with index

for index, value in enumerate(mylist):
    print(index, value)

Enumerate from a different start index

mylist = [5,6,7]

for index, value in enumerate(mylist, start= 1):
    print(index, value)

1 5
2 6
3 7

Dictionary iterate

for k, v in d.items():
    print(k, v)


Written with StackEdit.