Iterating through list of list

This traverse generator function can be used to iterate over all the values: def traverse(o, tree_types=(list, tuple)): if isinstance(o, tree_types): for value in o: for subvalue in traverse(value, tree_types): yield subvalue else: yield o data = [(1,1,(1,1,(1,”1″))),(1,1,1),(1,),1,(1,(1,(“1”,)))] print list(traverse(data)) # prints [1, 1, 1, 1, 1, ‘1’, 1, 1, 1, 1, 1, 1, 1, ‘1’] … Read more

Check list monotonicity

Are repeated values (e.g. [1, 1, 2]) monotonic? If yes: def non_decreasing(L): return all(x<=y for x, y in zip(L, L[1:])) def non_increasing(L): return all(x>=y for x, y in zip(L, L[1:])) def monotonic(L): return non_decreasing(L) or non_increasing(L) If no: def strictly_increasing(L): return all(x<y for x, y in zip(L, L[1:])) def strictly_decreasing(L): return all(x>y for x, y … Read more

Find a value in a list [duplicate]

As for your first question: “if item is in my_list:” is perfectly fine and should work if item equals one of the elements inside my_list. The item must exactly match an item in the list. For instance, “abc” and “ABC” do not match. Floating point values in particular may suffer from inaccuracy. For instance, 1 … Read more

How to sort a list of dictionaries by a value of the dictionary in Python?

The sorted() function takes a key= parameter newlist = sorted(list_to_be_sorted, key=lambda d: d[‘name’]) Alternatively, you can use operator.itemgetter instead of defining the function yourself from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’)) For completeness, add reverse=True to sort in descending order newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’), reverse=True)