What is Python buffer type for?

An example usage: The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn’t take extra storage space – it references a slice of the string. This isn’t very useful for short strings like this, but it can be necessary when using large amounts of data. This example … Read more

How to leave/exit/deactivate a Python virtualenv

Usually, activating a virtualenv gives you a shell function named: 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 upon your version of conda. Recent versions (like … Read more

How to fix ‘ValueError: list.remove(x): x not in list’ error in Python

list.remove takes a single argument, which is the item you want to remove. From the docs: https://docs.python.org/3/tutorial/datastructures.html list.remove(x)Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item. But “Maths, 76” is not an element in your list, hence you get the error ValueError: list.remove(x): x not in … Read more

How to prompt for user input and read command-line arguments

To read user input you can try the cmd module for easily creating a mini-command line interpreter (with help texts and autocompletion) and raw_input (input for Python 3+) for reading a line of text from the user. Command line inputs are in sys.argv. Try this in your script: There are two modules for parsing command line options: (deprecated since Python 2.7, use argparse instead) and getopt. If … Read more

Relative paths in Python

In the file that has the script, you want to do something like this: This will give you the absolute path to the file you’re looking for. Note that if you’re using setuptools, you should probably use its package resources API instead. UPDATE: I’m responding to a comment here so I can paste a code sample. 🙂 … Read more