How do I determine if an object has an attribute in Python?

Try hasattr(): if hasattr(a, ‘property’): a.property See zweiterlinde’s answer below, who offers good advice about asking forgiveness! A very pythonic approach! The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except … Read more

How to leave/exit/deactivate a Python virtualenv

Usually, activating a virtualenv gives you a shell function named: $ deactivate which puts things back to normal. I have just looked specifically again at the code for virtualenvwrapper, and, yes, it too supports deactivate as the way to escape from all virtualenvs. If you are trying to leave an Anaconda environment, the command depends … Read more

How to print without a newline or space

In Python 3, you can use the sep= and end= parameters of the print function: To not add a newline to the end of the string: print(‘.’, end=”) To not add a space between all the function arguments you want to print: print(‘a’, ‘b’, ‘c’, sep=”) You can pass any string to either parameter, and … Read more

How do I sort a list of dictionaries by a value of the dictionary?

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)

How do I get the last element of a list?

some_list[-1] is the shortest and most Pythonic. In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element. You can also set list elements … Read more