Skip to content
Advertisement

How do I generate all permutations of a list?

How do I generate all the permutations of a list? For example: Answer Use itertools.permutations from the standard library: Adapted from here is a demonstration of how itertools.permutations might be implemented: A couple of alternative approaches are listed in the documentation of itertools.permutations. Here’s one: And another, based on itertools.product:

How do I execute a program or call a system command?

How do I call an external command within Python as if I had typed it in a shell or command prompt? Answer Use the subprocess module in the standard library: The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout, stderr, the “real” status code, better error handling, etc…). Even the documentation for

Is there a benefit to defining a class inside another class in Python?

What I’m talking about here are nested classes. Essentially, I have two classes that I’m modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn’t necessarily mean nesting, right? I have code that looks something like this: But now I’m wondering if there’s a situation where nesting would be better. Something like:

Sending mail from Python using SMTP

I’m using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I’m missing ? Answer The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to

How to retrieve an element from a set without removing it?

Suppose the following: How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it – something I can only be sure of after an asynchronous call to another host. Quick and dirty: But do you know of a better way?

How do I check if a list is empty?

This question’s answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions. For example, if passed the following: How do I check to see if a is empty? Answer Using the implicit booleanness of the empty list is quite Pythonic.

Best way to extract text from a Word doc without using COM/automation?

Is there a reasonable way to extract plain text from a Word file that doesn’t depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform – that’s non-negotiable in this case.) Antiword seems like it might be a reasonable option, but it seems like it might be abandoned. A Python solution would

Advertisement