Why not inherit from List?

There are some good answers here. I would add to them the following points. What is the correct C# way of representing a data structure, which, “logically” (that is to say, “to the human mind”) is just a list of things with a few bells and whistles? Ask any ten non-computer-programmer people who are familiar … Read more

Why is it string.join(list) instead of list.join(string)?

It’s because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the “joiner” must be strings. For example: ‘_’.join([‘welcome’, ‘to’, ‘stack’, ‘overflow’]) ‘_’.join((‘welcome’, ‘to’, ‘stack’, ‘overflow’)) ‘welcome_to_stack_overflow’ Using something other than strings will raise the following error: TypeError: sequence item 0: expected str instance, int found

How can I randomly select an item from a list?

Use random.choice(): import random foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] print(random.choice(foo)) For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice(): import secrets foo = [‘battery’, ‘correct’, ‘horse’, ‘staple’] print(secrets.choice(foo)) secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class: import random … 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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)