Input:
Why is 'x' in ('x',) faster than 'x' == 'x'? >>> timeit.timeit("'x' in ('x',)")
0.04869917374131205
>>> timeit.timeit("'x' == 'x'")
0.06144205736110564

Also works for tuples with multiple elements, both versions seem to grow linearly:
>>> timeit.timeit("'x' in ('x', 'y')")
0.04866674801541748
>>> timeit.timeit("'x' == 'x' or 'x' == 'y'")
0.06565782838087131
>>> timeit.timeit("'x' in ('y', 'x')")
0.08975995576448526
>>> timeit.timeit("'x' == 'y' or 'x' == 'y'")
0.12992391047427532

Based on this, I think I should totally start using in everywhere instead of ==!

Output:
As I mentioned to David Wolever, there's more to this than meets the eye; both methods dispatch to is; you can prove this by doing
min(Timer("x == x", setup="x = 'a' * 1000000").repeat(10, 10000))
#>>> 0.00045456900261342525

min(Timer("x == y", setup="x = 'a' * 1000000; y = 'a' * 1000000").repeat(10, 10000))
#>>> 0.5256857610074803

The first can only be so fast because it checks by identity.
To find out why one would take longer than the other, let's trace through execution.
They both start in ceval.c, from COMPARE_OP since that is the bytecode involved
TARGET(COMPARE_OP) {
    PyObject *right = POP();
    PyObject *left = TOP();
    PyObject *res = cmp_outcome(oparg, left, right);
    Py_DECREF(left);
    Py_DECREF(right);
    SET_TOP(res);
    if (res == NULL)
        goto error;
    PREDICT(POP_JUMP_IF_FALSE);
    PREDICT(POP_JUMP_IF_TRUE);
    DISPATCH();
}

This pops the values from the stack (technically it only pops one)
PyObject *right = POP();
PyObject *left = TOP();

and runs the compare:
PyObject *res = cmp_outcome(oparg, left, right);

cmp_outcome is this:
static PyObject *
cmp_outcome(int op, PyObject *v, PyObject *w)
{
    int res = 0;
    switch (op) {
    case PyCmp_IS: ...
    case PyCmp_IS_NOT: ...
    case PyCmp_IN:
        res = PySequence_Contains(w, v);
        if (res < 0)
            return NULL;
        break;
    case PyCmp_NOT_IN: ...
    case PyCmp_EXC_MATCH: ...
    default:
        return PyObject_RichCompare(v, w, op);
    }
    v = res ? Py_True : Py_False;
    Py_INCREF(v);
    return v;
}

This is where the paths split. The PyCmp_IN branch does
int
PySequence_Contains(PyObject *seq, PyObject *ob)
{
    Py_ssize_t result;
    PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
    if (sqm != NULL && sqm->sq_contains != NULL)
        return (*sqm->sq_contains)(seq, ob);
    result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
    return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
}

Note that a tuple is defined as
static PySequenceMethods tuple_as_sequence = {
    ...
    (objobjproc)tuplecontains,                  /* sq_contains */
};

PyTypeObject PyTuple_Type = {
    ...
    &tuple_as_sequence,                         /* tp_as_sequence */
    ...
};

So the branch
if (sqm != NULL && sqm->sq_contains != NULL)

will be taken and *sqm->sq_contains, which is the function (objobjproc)tuplecontains, will be taken.
This does
static int
tuplecontains(PyTupleObject *a, PyObject *el)
{
    Py_ssize_t i;
    int cmp;

    for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
        cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i),
                                           Py_EQ);
    return cmp;
}

...Wait, wasn't that PyObject_RichCompareBool what the other branch took? Nope, that was PyObject_RichCompare.
That code path was short so it likely just comes down to the speed of these two. Let's compare.
int
PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
{
    PyObject *res;
    int ok;

    /* Quick result when objects are the same.
       Guarantees that identity implies equality. */
    if (v == w) {
        if (op == Py_EQ)
            return 1;
        else if (op == Py_NE)
            return 0;
    }

    ...
}

The code path in PyObject_RichCompareBool pretty much immediately terminates. For PyObject_RichCompare, it does
PyObject *
PyObject_RichCompare(PyObject *v, PyObject *w, int op)
{
    PyObject *res;

    assert(Py_LT <= op && op <= Py_GE);
    if (v == NULL || w == NULL) { ... }
    if (Py_EnterRecursiveCall(" in comparison"))
        return NULL;
    res = do_richcompare(v, w, op);
    Py_LeaveRecursiveCall();
    return res;
}

The Py_EnterRecursiveCall/Py_LeaveRecursiveCall combo are not taken in the previous path, but these are relatively quick macros that'll short-circuit after incrementing and decrementing some globals.
do_richcompare does:
static PyObject *
do_richcompare(PyObject *v, PyObject *w, int op)
{
    richcmpfunc f;
    PyObject *res;
    int checked_reverse_op = 0;

    if (v->ob_type != w->ob_type && ...) { ... }
    if ((f = v->ob_type->tp_richcompare) != NULL) {
        res = (*f)(v, w, op);
        if (res != Py_NotImplemented)
            return res;
        ...
    }
    ...
}

This does some quick checks to call v->ob_type->tp_richcompare which is
PyTypeObject PyUnicode_Type = {
    ...
    PyUnicode_RichCompare,      /* tp_richcompare */
    ...
};

which does
PyObject *
PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
{
    int result;
    PyObject *v;

    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
        Py_RETURN_NOTIMPLEMENTED;

    if (PyUnicode_READY(left) == -1 ||
        PyUnicode_READY(right) == -1)
        return NULL;

    if (left == right) {
        switch (op) {
        case Py_EQ:
        case Py_LE:
        case Py_GE:
            /* a string is equal to itself */
            v = Py_True;
            break;
        case Py_NE:
        case Py_LT:
        case Py_GT:
            v = Py_False;
            break;
        default:
            ...
        }
    }
    else if (...) { ... }
    else { ...}
    Py_INCREF(v);
    return v;
}

Namely, this shortcuts on left == right... but only after doing
    if (!PyUnicode_Check(left) || !PyUnicode_Check(right))

    if (PyUnicode_READY(left) == -1 ||
        PyUnicode_READY(right) == -1)

All in all the paths then look something like this (manually recursively inlining, unrolling and pruning known branches)
POP()                           # Stack stuff
TOP()                           #
                                #
case PyCmp_IN:                  # Dispatch on operation
                                #
sqm != NULL                     # Dispatch to builtin op
sqm->sq_contains != NULL        #
*sqm->sq_contains               #
                                #
cmp == 0                        # Do comparison in loop
i < Py_SIZE(a)                  #
v == w                          #
op == Py_EQ                     #
++i                             #
cmp == 0                        #
                                #
res < 0                         # Convert to Python-space
res ? Py_True : Py_False        #
Py_INCREF(v)                    #
                                #
Py_DECREF(left)                 # Stack stuff
Py_DECREF(right)                #
SET_TOP(res)                    #
res == NULL                     #
DISPATCH()                      #

vs
POP()                           # Stack stuff
TOP()                           #
                                #
default:                        # Dispatch on operation
                                #
Py_LT <= op                     # Checking operation
op <= Py_GE                     #
v == NULL                       #
w == NULL                       #
Py_EnterRecursiveCall(...)      # Recursive check
                                #
v->ob_type != w->ob_type        # More operation checks
f = v->ob_type->tp_richcompare  # Dispatch to builtin op
f != NULL                       #
                                #
!PyUnicode_Check(left)          # ...More checks
!PyUnicode_Check(right))        #
PyUnicode_READY(left) == -1     #
PyUnicode_READY(right) == -1    #
left == right                   # Finally, doing comparison
case Py_EQ:                     # Immediately short circuit
Py_INCREF(v);                   #
                                #
res != Py_NotImplemented        #
                                #
Py_LeaveRecursiveCall()         # Recursive check
                                #
Py_DECREF(left)                 # Stack stuff
Py_DECREF(right)                #
SET_TOP(res)                    #
res == NULL                     #
DISPATCH()                      #

Now, PyUnicode_Check and PyUnicode_READY are pretty cheap since they only check a couple of fields, but it should be obvious that the top one is a smaller code path, it has fewer function calls, only one switch
statement and is just a bit thinner.
TL;DR:
Both dispatch to if (left_pointer == right_pointer); the difference is just how much work they do to get there. in just does less.


Input:
How do I run Python code from Sublime Text 2? I want to set up a complete Python IDE in Sublime Text 2.
I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ?

Output:
Tools -> Build System -> (choose) Python then:
To Run:
      Tools -> Build

      -or-

      Ctrl + B

      CMD + B  (OSX)

This would start your file in the console which should be at the bottom of the editor.
To Stop:
       Ctrl + Break or Tools -> Cancel Build

You can find out where your Break key is here:  http://en.wikipedia.org/wiki/Break_key.
Note: CTRL + C will NOT work.
What to do when Ctrl + Break does not work:
Go to:

Preferences -> Key Bindings - User

and paste the line below:
{"keys": ["ctrl+shift+c"], "command": "exec", "args": {"kill": true} }

Now, you can use ctrl+shift+c instead of CTRL+BREAK


Input:
How to print a class or objects of class using print()? I am learning the ropes in Python. When I try to print an object of class Foobar using the print() function, I get an output like this:
<__main__.Foobar instance at 0x7ff2a18c>

Is there a way I can set the printing behaviour (or the string representation) of a class and its objects? For instance, when I call print() on a class object, I would like to print its data members in a certain format. How to achieve this in Python?
If you are familiar with C++ classes, the above can be achieved for the standard ostream by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class.

Output:
>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print t
member of Test

The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.
If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.


Input:
Convert a list of characters into a string If I have a list of chars:
a = ['a','b','c','d']

How do I convert it into a single string?
a = 'abcd'

Output:
Use the join method of the empty string to join all of the strings together with the empty string in between, like so:
>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'


Input:
What's the idiomatic syntax for prepending to a short python list? list.append() is the obvious choice for adding to the end of a list.  Here's a reasonable explanation for the missing list.prepend().  Assuming my list is short and performance concerns are negligible, is
list.insert(0, x)

or
list[0:0] = [x]

idiomatic?

Output:
The s.insert(0, x) form is the most common.
Whenever you see it though, it may be time to consider using a collections.deque instead of a list.


Input:
Which exception should I raise on bad/illegal argument combinations in Python? I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:
def import_to_orm(name, save=False, recurse=False):
    """
    :param name: Name of some external entity to import.
    :param save: Save the ORM object before returning.
    :param recurse: Attempt to import associated objects as well. Because you
        need the original object to have a key to relate to, save must be
        `True` for recurse to be `True`.
    :raise BadValueError: If `recurse and not save`.
    :return: The ORM object.
    """
    pass

The only annoyance with this is that every package has its own, usually slightly differing BadValueError. I know that in Java there exists java.lang.IllegalArgumentException -- is it well understood that everybody will be creating their own BadValueErrors in Python or is there another, preferred method?

Output:
I would just raise ValueError, unless you need a more specific exception..
def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that?


Input:
Python urlencode querystring I am trying to urlencode this string before I submit.
queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];

Output:
Python 2
What you're looking for is urllib.quote_plus:
>>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'

Python 3
In Python 3, you the urllib package has been broken into smaller components. You'll use urllib.parse.quote_plus() (note the parse child module).


Input: How to check Django version I have to use Python and Django for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. But how do I make sure whether Django uses the 2.6 or 2.7 version and what version of modules Django uses?

Output:
Django 1.5 supports Python 2.6.5 and later.
If you're under Linux and want to check the Python version you're using, run python -V from the command line.
If you want to check the Django version, open a Python console and type
import django
django.VERSION


Input:
Fastest way to check if a value exist in a list I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know all values in the list are unique like my example.
My first methods I try is(3.8sec in my real code):
a = [4,2,3,1,5,6]

if a.count(7) == 1:
    b=a.index(7)
    "Do something with variable b"

My second methods I try is (2x faster:1.9sec on my real code):
a = [4,2,3,1,5,6]

try:
    b=a.index(7)
except ValueError:
    "Do nothing"
Else:
    "Do something with variable b"

Proposed methods from S.O. user (2.74sec on my real code):
a = [4,2,3,1,5,6]
if 7 in a:
    a.index(7)

In my real code , first method take 3.81sec and the second methods take 1.88sec.
It's a good improvement but:
I'm a beginner with Python/scripting and I want to know if a fastest way exist to do the same things and save more process time?
More specific explication for my application:
In the API of blender a can access to a list of particles:
particles = [1,2,3,4...etc.]

From there , I can access to it's location:
particles[x].location = [x,y,z]

And I test for each particles if a neighbour exist by searching
in the location of each particles like:
if [x+1,y,z] in particles.location
    "find the identity of this neighbour particles in x:the index
    of the particles array"
    particles.index([x+1,y,z])

Output:
7 in a

Clearest and fastest way to do it.
You can also consider using a set, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)


Input: How do I get my python program to sleep for 50 milliseconds? How do I get my python program to sleep for 50 milliseconds?

Output:
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from time import sleep
>>> sleep(0.05)
>>>


Input:
What's the difference between eval, exec, and compile in Python? I've been looking at dynamic evaluation of Python code, and come across the eval() and compile() functions, and the exec statement.
Can someone please explain the difference between eval and exec, and how the different modes of compile() fit in?

Output:
exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:
exec('print(5)')           # prints 5.
# exec 'print 5'     if you use Python 2.x, nor the exec neither the print is a function there
exec('print(5)\nprint(6)')  # prints 5{newline}6.
exec('if True: print(6)')  # prints 6.
exec('5')                 # does nothing and returns nothing.

eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:
x = eval('5')              # x <- 5
x = eval('%d + 6' % x)     # x <- 11
x = eval('abs(%d)' % -100) # x <- 100
x = eval('x = 5')          # INVALID; assignment is not an expression.
x = eval('if 1: x = 4')    # INVALID; if is a statement, not an expression.

compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.
compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.
compile(string, '', 'single') is like the exec mode, but it will ignore everything except for the first statement. Note that an if/else statement with its results is considered a single statement.


Input: How to find out the number of CPUs using python I want to know the number of CPUs on the local machine using Python. The result should be user/real as output by time(1) when called with an optimally scaling userspace-only program.

Output:
If you have python with a version >= 2.6 you can simply use
import multiprocessing

multiprocessing.cpu_count()

http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count


Input:
What is the best way to remove accents in a Python unicode string? I have a Unicode string in Python, and I would like to remove all the accents (diacritics).
I found on the Web an elegant way to do this in Java:

convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)
remove all the characters whose Unicode type is "diacritic".

Do I need to install a library such as pyICU or is this possible with just the python standard library?  And what about python 3?
Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.

Output:
How about this:
import unicodedata
def strip_accents(s):
   return ''.join(c for c in unicodedata.normalize('NFD', s)
                  if unicodedata.category(c) != 'Mn')

This works on greek letters, too:
>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>>

The character category "Mn" stands for Nonspacing_Mark, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).
And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".


Input:
Simple Digit Recognition OCR in OpenCV-Python I am trying to implement a "Digit Recognition OCR" in OpenCV-Python (cv2). It is just for learning purposes. I would like to learn both KNearest and SVM features in OpenCV.
I have 100 samples (i.e. images) of each digit. I would like to train with them.
There is a sample letter_recog.py that comes with OpenCV sample. But i still couldn't figure out on how to use it. I don't understand what are the samples, responses etc. Also, it loads a txt file at first, which i didn't understand first.
Later on searching a little bit, i could find a letter_recognition.data in cpp samples. I used it and made a code for cv2.KNearest in the model of letter_recog.py (just for testing):
import numpy as np
import cv2

fn = 'letter-recognition.data'
a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
samples, responses = a[:,1:], a[:,0]

model = cv2.KNearest()
retval = model.train(samples,responses)
retval, results, neigh_resp, dists = model.find_nearest(samples, k = 10)
print results.ravel()

It gave me an array of size 20000, i don't understand what it is.
Questions:
1) What is letter_recognition.data file ? How to build that file from my own data set?
2) What does results.reval() denote?
3) How we can write a simple digit recognition tool using letter_recognition.data file (either KNearest or SVM)?

Output:
Well, I decided to workout myself on my question to solve above problem. What i wanted is to implement a simpl OCR using KNearest or SVM features in OpenCV. And below is what i did and how. ( it is just for learning how to use KNearest for simple OCR purposes).
1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.
It contains a letter, along with 16 features of that letter.
And this SOF helped me to find it. These 16 features are explained in the paperLetter Recognition Using Holland-Style Adaptive Classifiers.
( Although i didn't understand some of the features at end)
2) Since i knew, without understanding all those features, it is difficult to do that method. i tried some other papers, but all were a little difficult for a beginner.
So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, i just wanted it to work, at least with the least accuracy)
I took below image for my training data:

( I know the amount of training data is less. But, since all letters are of same font and size, i decided to try on this).
To prepare the data for training, i made a small code in OpenCV. It does following things:
a) It loads the image.
b) Selects the digits ( obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
c) Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in box.
d) Once corresponding digit key is pressed, it resizes this box to 10x10 and saves 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here,  responses).
e) Then save both the arrays in separate txt files.
At the end of manual classification of digits, all the digits in the train data( train.png) are labeled manually by ourselves, image will look like below:

Below is the code i used for above purpose ( of course, not so clean):
import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)

        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.
For testing part i used below image, which has same type of letters i used to train.

For training we do as follows:
a) Load the txt files we already saved earlier
b) create a instance of classifier we are using ( here, it is KNearest)
c) Then we use KNearest.train function to train the data
For testing purposes, we do as follows:
a) We load the image used for testing
b) process the image as earlier and extract each digit using contour methods
c) Draw bounding box for it, then resize to 10x10, and store its pixel values in an array as done earlier.
d) Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognises the correct digit.)
I included last two steps ( training and testing) in single code below:
import cv2
import numpy as np

#######   training part    ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked , below is the result i got:

Here it worked with 100% accuracy, for which the reason, i assume, is all digits are of same kind and same size.
But any way, this is a good start to go for beginners ( i hope so).


Input:
How do I make python to wait for a pressed key I want my script to wait until the user presses any key.
How do I do that?

Output:
One way to do this in Python 2, is to use raw_input():
raw_input("Press Enter to continue...")

In python3 it's just input()


Input: Find all packages installed with easy_install/pip? Is there a way to find all Python PyPI packages that were installed with easy_install or pip?  I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian).

Output:
pip freeze will output a list of installed packages and their versions. It also allows you to write those packages to a file that can later be used to set up a new environment.
http://www.pip-installer.org/en/latest/index.html#freezing-requirements


Input:
Short Description of Scoping Rules What exactly are the Python scoping rules?
If I have some code:
code1
class Foo:
   code2
   def spam.....
      code3
      for code4..:
       code5
       x()

Where is x found?  Some possible choices include the list above:

In the enclosing source file
In the class namespace
In the function definition
In the for loop index variable
Inside the for loop

Also there is the context during execution, when the function spam is passed somewhere else.  And maybe lambda functions pass a bit differently?
There must be a simple reference or algorithm somewhere.  It's a confusing world for intermediate Python programmers.

Output:
Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply)
LEGB Rule.
L, Local â Names assigned in any way within a function (def or lambda)), and not declared global in that function.
E, Enclosing function locals â Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer.
G, Global (module) â Names assigned at the top-level of a module file, or declared global in a def within the file.
B, Built-in (Python) â Names preassigned in the built-in names module : open,range,SyntaxError,...
So, in the case of
code1
class Foo:
   code2
   def spam.....
      code3
      for code4..:
       code5
       x()

The for loop does not have its own namespace. In LEGB order, the scopes would be
L : local, in the current def.
E : Enclosed function, any enclosing functions (if def spam was in another def)
G : Global. Were there any declared globally in the module?
B : Any builtin x() in Python.


Input: Does Python have an ordered set? Python has an ordered dictionary, what about an ordered set?

Output:
There is an ordered set recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.
OrderedSet([1, 2, 3])

This is a MutableSet, so the signature for .union doesn't match that of set, but since it includes __or__ something similar can easily be added:
@staticmethod
def union(*sets):
    union = OrderedSet()
    union.union(*sets)
    return union

def union(self, *sets):
    for set in sets:
        self |= set


Input: time.sleep -- sleeps thread or process? In Python for the *nix, does time.sleep() block the thread or the process?

Output:
It blocks the thread.  If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep(), the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps.  You can also test this with a simple python program:
import time
from threading import Thread

class worker(Thread):
    def run(self):
    	for x in xrange(0,11):
    		print x
    		time.sleep(1)

class waiter(Thread):
    def run(self):
    	for x in xrange(100,103):
    		print x
    		time.sleep(5)

def run():
    worker().start()
    waiter().start()

Which will print:
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102


Input:
Python list of lists, changes reflected across sublists unexpectedly I needed to create a list of lists in Python, so I typed the following:
myList = [[1] * 4] * 3

The list looked like this:
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]

Then I changed one of the innermost values:
myList[0][0] = 5

Now my list looks like this:
[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]

which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?

Output:
When you write [x]*3 you get, essentially, the list [x, x, x]. That is, a list with 3 references to the same x. When you then modify this single x it is visible via all three references to it.
To fix it, you need to make sure that you create a new list at each position. One way to do it is
[[1]*4 for n in range(3)]


Input:
How to break out of multiple loops in Python? Given the following code (that doesn't work):
while True:
    #snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y": break 2 #this doesn't work :(
        if ok == "n" or ok == "N": break
    #do more processing with menus and stuff

Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?
Edit-FYI: get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns stdin.readline().strip()

Output: My first instinct would be to refactor the nested loop into a function and use return to break out.


Input:
How to install python3 version of package via pip on Ubuntu? I have both python2.7 and python3.2 installed in Ubuntu 12.04.
The symbolic link python links to python2.7.
When I type:
sudo pip install package-name

It will default install python2 version of package-name.
Some package supports both python2 and python3.
How to install python3 version of package-name via pip?

Output:
Ubuntu 12.10+ and Fedora 13+ have a package called python3-pip which will install pip-3.2 (or pip-3.3, pip-3.4 or pip3 for newer versions) without needing this jumping through hoops.

I came across this and fixed this without needing the likes of wget or virtualenvs (assuming Ubuntu 12.04):

Install package python3-setuptools: run sudo aptitude install python3-setuptools, this will give you the command easy_install3.
Install pip using Python 3's setuptools: run sudo easy_install3 pip, this will give you the command pip-3.2 like kev's solution.
Install your PyPI packages: run sudo pip-3.2 install <package> (installing python packages into your base system requires root, of course).
â¦
Profit!


Input:
In Matplotlib, what does the argument mean in fig.add_subplot(111)? Sometimes I come across code such as this:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = plt.figure()
fig.add_subplot(111)
plt.scatter(x, y)
plt.show()

Which produces:

I've been reading the documentation like crazy but I can't find an explanation for the 111. sometimes I see a 212.
What does the argument of fig.add_subplot() mean?

Output:
I think this would be best explained by the following picture:

To initialize the above, one would type:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221)   #top left
fig.add_subplot(222)   #top right
fig.add_subplot(223)   #bottom left
fig.add_subplot(224)   #bottom right
plt.show()

EDIT: Some additional information
The following combinations produce asymmetrical arrangements of subplots.
subplot(2,2,[1 3])
subplot(2,2,2)
subplot(2,2,4)

You can also use the colon operator to specify multiple locations if they are in sequence.
subplot(2,2,1:2)
subplot(2,2,3)
subplot(2,2,4)

Reference here


Input:
python open built-in function: difference between modes a, a+, w, w+, and r+? In the python built-in open function, what is the exact difference between the modes w, a, w+, a+, and r+?
In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.

Output:
The opening modes are exactly the same that C fopen() std library function.
The BSD fopen manpage defines them as follows:
 The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.


Input:
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? I need a way to tell what mode the shell is in from within the shell.
I've tried looking at the platform module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods described here to force 32bit mode).

Output:
UPDATED:
One way is to look at sys.maxsize as documented here:
$ python-32 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffff', False)
$ python-64 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffffffffffff', True)

sys.maxsize was introduced in Python 2.6.  If you need a test for older systems, this slightly more complicated test should work on all Python 2 and 3 releases:
$ python-32 -c 'import struct;print( 8 * struct.calcsize("P"))'
32
$ python-64 -c 'import struct;print( 8 * struct.calcsize("P"))'
64

BTW, you might be tempted to use platform.architecture() for this.  Unfortunately, its results are not always reliable, particularly in the case of OS X universal binaries.
$ arch -x86_64 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit True
$ arch -i386 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit False


Input:
Setting the correct encoding when piping stdout in Python When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:
# -*- coding: utf-8 -*-
print u"Ã¥Ã¤Ã¶"

will work fine when run normally, but fail with:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

when used in a pipe sequence.
What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using?
The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u"Ã¥Ã¤Ã¶"

Is there a better way to make piping work?

Output:
First, regarding this solution:
# -*- coding: utf-8 -*-
print u"Ã¥Ã¤Ã¶".encode('utf-8')

It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.
A better solution is to change sys.stdout at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)


Input: Difference between Python's Generators and Iterators What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.

Output:
iterator is a more general concept: any object whose class has a next method (__next__ in Python 3) and an __iter__ method that does return self.
Every generator is an iterator, but not vice versa.  A generator is built by calling a function that has one or more yield expressions (yield statements, in Python 2.5 and earlier), and is an object that meets the previous paragraph's definition of an iterator.
You may want to use a custom iterator, rather than a generator, when you need a class with somewhat complex state-maintaining behavior, or want to expose other methods besides next (and __iter__ and __init__).  Most often, a generator (sometimes, for sufficiently simple needs, a generator expression) is sufficient, and it's simpler to code because state maintenance (within reasonable limits) is basically "done for you" by the frame getting suspended and resumed.
For example, a generator such as:
def squares(start, stop):
    for i in xrange(start, stop):
        yield i * i

generator = squares(a, b)

or the equivalent generator expression (genexp)
generator = (i*i for i in xrange(a, b))

would take more code to build as a custom iterator:
class Squares(object):
    def __init__(self, start, stop):
       self.start = start
       self.stop = stop
    def __iter__(self): return self
    def next(self):
       if self.start >= self.stop:
           raise StopIteration
       current = self.start * self.start
       self.start += 1
       return current

iterator = Squares(a, b)

But, of course, with class Squares you could easily offer extra methods, i.e.
    def current(self):
       return self.start

if you have any actual need for such extra functionality in your application.


Input: Python: user input and commandline arguments How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?

Output:
var = raw_input("Please enter something: ")
print "you entered", var


Input:
Elegant ways to support equivalence ("equality") in Python classes When writing custom classes it is often important to allow equivalence by means of the == and != operators. In Python, this is made possible by implementing the __eq__ and __ne__ special methods, respectively. The easiest way I've found to do this is the following method:
class Foo:
    def __init__(self, item):
        self.item = item

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing __dict__s?
Note: A bit of clarification--when __eq__ and __ne__ are undefined, you'll find this behavior:
>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
False

That is, a == b evaluates to False because it really runs a is b, a test of identity (i.e., "Is a the same object as b?").
When __eq__ and __ne__ are defined, you'll find this behavior (which is the one we're after):
>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
True

Output:
You need to be careful with inheritance:
>>> class Foo:
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__
        else:
            return False

>>> class Bar(Foo):pass

>>> b = Bar()
>>> f = Foo()
>>> f == b
True
>>> b == f
False

Check types more strictly, like this:
def __eq__(self, other):
    if type(other) is type(self):
        return self.__dict__ == other.__dict__
    return False

Besides that, your approach will work fine, that's what special methods are there for.


Input:
How to use 'super' in Python? Can someone explain to me the difference between doing:
class Child(SomeBaseClass):
    def __init__(self):
        super(Child, self).__init__()

and this:
class Child(SomeBaseClass):
    def __init__(self):
        SomeBaseClass.__init__(self)

I've seen super being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.

Output:
The benefits of super() in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
However, it's almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child and a mixin, their code would not work properly.


Input:
How do I use raw_input in Python 3 import sys
print (sys.platform)
print (2 ** 100)
raw_input( )

I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1
What should I do to fix this?

Output:
raw_input() was renamed to input()
From http://docs.python.org/dev/py3k/whatsnew/3.0.html


Input:
How do you convert a Python time.struct_time object into a datetime object? How do you convert a Python time.struct_time object into a datetime.datetime object?
I have a library that provides the first one and a second library that wants the second one...

Output:
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from time import mktime
from datetime import datetime

dt = datetime.fromtimestamp(mktime(struct))


Input:
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syncdb, I get this error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
  execute_manager(settings)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
  utility.execute()
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 257, in fetch_command
  klass = load_command_class(app_name, subcommand)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 67, in load_command_class
  module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/contrib/contenttypes/generic.py", line 6, in <module>
  from django.db import connection
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/__init__.py", line 75, in <module>
  connection = connections[DEFAULT_DB_ALIAS]
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 91, in __getitem__
  backend = load_backend(db['ENGINE'])
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 32, in load_backend
  return import_module('.base', backend_name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module>
  raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I've also installed the MySQL for Python adapter, but to no avail (maybe I installed it improperly?).
Anyone dealt with this before?

Output:
I had the same error and pip install MySQL-python solved it for me.
Alternate installs:

If you don't have pip, easy_install MySQL-python should work.
If your python is managed by a packaging system, you might have to use
that system (e.g. sudo apt-get install ...)

Below, Soli notes that if you receive the following error:

EnvironmentError: mysql_config not found

... then you have a further system dependency issue. Solving this will vary from system to system, but for Debian-derived systems:
sudo apt-get install python-mysqldb


Input:
What is the python "with" statement designed for? I came across the Python with statement for the first time today.  I've been using Python lightly for several months and didn't even know of its existence!  Given its somewhat obscure status, I thought it would be worth asking:

What is the Python with statement
designed to be used for?
What do
you use it for?
Are their any
gotchas I need to be aware of, or
common anti-patterns associated with
its use?  Any cases where it is better use try..finally than with?
Why isn't it used more widely?
Which standard library classes are compatible with it?

Output:
I believe this has already been answered by other users before me, so I only add it for the sake of completeness: the with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. More details can be found in PEP 343. For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow. The with statement can thus be used in ways similar to the RAII pattern in C++: some resource is acquired by the with statement and released when you leave the with context.
Some examples are: opening files using with open(filename) as fp:, acquiring locks using with lock: (where lock is an instance of threading.Lock). You can also construct your own context managers using the contextmanager decorator from contextlib. For instance, I often use this when I have to change the current directory temporarily and then return to where I was:
from contextlib import contextmanager
import os

@contextmanager
def working_directory(path):
    current_dir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(current_dir)

with working_directory("data/stuff"):
    # do something within data/stuff
# here I am back again in the original working directory

Here's another example that temporarily redirects sys.stdin, sys.stdout and sys.stderr to some other file handle and restores them later:
from contextlib import contextmanager
import sys

@contextmanager
def redirected(**kwds):
    stream_names = ["stdin", "stdout", "stderr"]
    old_streams = {}
    try:
        for sname in stream_names:
            stream = kwds.get(sname, None)
            if stream is not None and stream != getattr(sys, sname):
                old_streams[sname] = getattr(sys, sname)
                setattr(sys, sname, stream)
        yield
    finally:
        for sname, stream in old_streams.iteritems():
            setattr(sys, sname, stream)

with redirected(stdout=open("/tmp/log.txt", "w")):
     # these print statements will go to /tmp/log.txt
     print "Test entry 1"
     print "Test entry 2"
# back to the normal stdout
print "Back to normal stdout again"

And finally, another example that creates a temporary folder and cleans it up when leaving the context:
from tempfile import mkdtemp
from shutil import rmtree

@contextmanager
def temporary_dir(*args, **kwds):
    name = mkdtemp(*args, **kwds)
    try:
        yield name
    finally:
        shutil.rmtree(name)

with temporary_dir() as dirname:
    # do whatever you want


Input:
Python: How to import other Python files How do I import other files in Python?

How exactly can I import a specific python file like import file.py?
How to import a folder instead of a specific file?
I want to load a Python file dynamically in runtime, based on user
input.
I want to know how to take from the file just one specific part.

For example, in main.py I have:
from extra import *

although this gives me all the file actions of extra.py when maybe all I want is
a single definition:
def gap():
    print
    print

What do I add to the import statement to just get gap from extra.py?

Output:
There are many ways to import a python file, all with their pros and cons.
Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.
I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #5
Example 1, Import a python module with python interpreter:

Put this in /home/el/foo/fox.py:
def what_does_the_fox_say():
  print("vixens cry")

Get into the python interpreter:
el@apollo:/home/el/foo$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
>>> import fox
>>> fox.what_does_the_fox_say()
vixens cry
>>>

You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

Put this in /home/el/foo2/mylib.py:
def moobar():
  print("hi")

Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py")
moobar()

run the file:
el@apollo:/home/el/foo$ python main.py
hi

The function moobar was imported from mylib.py and made available in main.py

Example 3, Use from ... import ... functionality:

Put this in /home/el/foo3/chekov.py:
def question():
  print "where are the nuclear wessels?"

Put this in /home/el/foo3/main.py:
from chekov import question
question()

Run it like this:
el@apollo:/home/el/foo3$ python main.py
where are the nuclear wessels?

If you defined other functions in chekov.py, they would not be available unless you import *

Example 4, Import riaa.py if it's in a different file location from where it is imported

Put this in /home/el/foo4/stuff/riaa.py:
def watchout():
  print "my message"

Put this in /home/el/foo4/main.py:
import sys
import os
sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
from riaa import *

watchout()

Run it:
el@apollo:/home/el/foo4$ python main.py
my message

That imports everything in the foreign file from a different directory.

Example 5, Import files in python with the bare import command:

Make a new directory /home/el/foo5/
Make a new directory /home/el/foo5/herp
Make an empty file named __init__.py under herp:
el@apollo:/home/el/foo5/herp$ touch __init__.py
el@apollo:/home/el/foo5/herp$ ls
__init__.py

Make a new directory /home/el/foo5/herp/derp
Under derp, make another __init__.py file:
el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
el@apollo:/home/el/foo5/herp/derp$ ls
__init__.py

Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:
def skycake():
  print "SkyCake evolves to stay just beyond the cognitive reach of " +
  "the bulk of men. SKYCAKE!!"

The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;
from herp.derp.yolo import skycake
skycake()

Run it:
el@apollo:/home/el/foo5$ python main.py
SkyCake evolves to stay just beyond the cognitive reach of the bulk
of men. SKYCAKE!!

The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.

If you want to see my post on how to include ALL .py files under a directory see here: http://stackoverflow.com/a/20753073/445131
Example 6, use os.system("python yourfile.py")
import os
os.system("python yourfile.py")

Bonus protip
whether you are using Mac, Linux or Windows, you need to be using python's idle editor as described here.  It will unlock your python world.  http://www.youtube.com/watch?v=DkW5CSZ_VII


Input: Does Python's time.time() return the local or UTC timestamp? Does time.time() in the Python time module return the system's time or the time in UTC?

Output:
The time.time() function returns the number of seconds since the epoch as seconds in UTC.
Here is some sample output I ran on my computer, converting it to a string as well.
Python 2.7.3 (default, Apr 24 2012, 00:00:54)
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> ts = time.time()
>>> print ts
1355563265.81
>>> import datetime
>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
>>> print st
2012-12-15 01:21:05
>>>

The ts variable is the time returned in seconds.  I then converted it to a string using the datetime library making it a string that is human readable.


Input:
Split string into a list in Python I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?
def split_line(text):

    # split the text
    words = text.split()

    # for each word in the line:
    for word in words:

        # print the word
        print(word)

Output:
Splits the string in text on delimiter: " ".
words = text.split()

Split the string in text on delimiter: ",".
words = text.split(",")

The words variable will be a list datatype and contain a list of words from text split on the delimiter.


Input:
What's the proper way to install pip, virtualenv, and distribute for Python? Short Question

What is the proper way to install pip, virtualenv, and distribute?

Background
In my answer to SO question 4314376, I recommended using ez_setup so that you could then install pip and virtualenv as follows:
curl -O http://peak.telecommunity.com/dist/ez_setup.py
sudo python ez_setup.py
sudo easy_install pip
sudo pip install virtualenv

I originally pulled these instructions from Jesse Noller's blog post So you want to use Python on the Mac?. I like the idea of keeping a clean global site-packages directory, so the only other packages I install there are  virtualenvwrapper and distribute. (I recently added distribute to my toolbox because of this Python public service announcement. To install these two packages, I used:
sudo pip install virtualenvwrapper
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py

No more setuptools and easy_install
To really follow that Python public service announcement, on a fresh Python install, I would do the following:
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py
sudo easy_install pip
sudo pip install virtualenv
sudo pip install virtualenvwrapper

Glyph's Rebuke
In a comment to my answer to SO question 4314376, SO user Glyph stated:

NO. NEVER EVER do sudo python setup.py install whatever. Write a ~/.pydistutils.cfg that puts your pip installation into ~/.local or something. Especially files named ez_setup.py tend to suck down newer versions of things like setuptools and easy_install, which can potentially break other things on your operating system.

Back to the short question
So Glyph's response leads me to my original question:

What is the proper way to install pip, virtualenv, and distribute?

Output:
You can do this without installing anything into python itself.
You don't need sudo or any privileges.
You don't need to edit any files.
Install virtualenv into a bootstrap virtual environment. Use the that virtual environment to create more. Since virtualenv ships with pip and distribute, you get everything from one install.

Download virtualenv:

http://pypi.python.org/pypi/virtualenv
https://pypi.python.org/packages/source/v/virtualenv/virtualenv-12.0.7.tar.gz
(or whatever is the latest version!)

Unpack the source tarball
Use the unpacked tarball to create a clean virtual environment. This virtual environment will be used to "bootstrap" others. All of your virtual environments will automatically contain pip and distribute.
Using pip, install virtualenv into that bootstrap environment.
Use that bootstrap environment to create more!

Here is an example in bash:
# Select current version of virtualenv:
VERSION=12.0.7
# Name your first "bootstrap" environment:
INITIAL_ENV=bootstrap
# Set to whatever python interpreter you want for your first environment:
PYTHON=$(which python)
URL_BASE=https://pypi.python.org/packages/source/v/virtualenv

# --- Real work starts here ---
curl -O $URL_BASE/virtualenv-$VERSION.tar.gz
tar xzf virtualenv-$VERSION.tar.gz
# Create the first "bootstrap" environment.
$PYTHON virtualenv-$VERSION/virtualenv.py $INITIAL_ENV
# Don't need this anymore.
rm -rf virtualenv-$VERSION
# Install virtualenv into the environment.
$INITIAL_ENV/bin/pip install virtualenv-$VERSION.tar.gz

Now you can use your "bootstrap" environment to create more:
# Create a second environment from the first:
$INITIAL_ENV/bin/virtualenv py-env1
# Create more:
$INITIAL_ENV/bin/virtualenv py-env2

Go nuts!
Note
This assumes you are not using a really old version of virtualenv.
Old versions required the flags --no-site-packges (and depending on the version of Python, --distribute). Now you can create your bootstrap environment with just python virtualenv.py path-to-bootstrap or python3 virtualenv.py path-to-bootstrap.


Input:
How to make a Python script standalone executable to run without ANY dependency? I'm building a Python application and don't want to force my clients to install Python and modules. I also want to make my application closed-source.
So, is there a way to compile Python scripts to standalone executables?

Output: You can use py2exe as already answered and use cython to convert your key .py files in .pyc, C compiled files, like .dll in Windows and .so in linux, much harder to revert than common .pyo and .pyc files (and also gain in performance!)


Input: Why isn't Python very good for functional programming? I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in this question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)

Output:
The question you reference asks which languages promote both OO and functional programming. Python does not promote functional programming even though it works fairly well.
The best argument against functional programming in Python is that imperative/OO use cases are carefully considered by Guido, while functional programming use cases are not. When I write imperative Python, it's one of the prettiest languages I know. When I write functional Python, it becomes as ugly and unpleasant as your average language that doesn't have a BDFL.
Which is not to say that it's bad, just that you have to work harder than you would if you switched to a language that promotes functional programming or switched to writing OO Python.
Here are the functional things I miss in Python:

Pattern matching
Tail recursion
Large library of list functions
Functional dictionary class
Automatic currying
Concise way to compose functions
Lazy lists
Simple, powerful expression syntax (Python's simple block syntax prevents Guido from adding it)

No pattern matching and no tail recursion mean your basic algorithms have to be written imperatively. Recursion is ugly and slow in Python.
A small list library and no functional dictionaries mean that you have to write a lot of stuff yourself.
No syntax for currying or composition means that point-free style is about as full of punctuation as explicitly passing arguments.
Iterators instead of lazy lists means that you have to know whether you want efficiency or persistence, and to scatter calls to list around if you want persistence. (Iterators are use-once)
Python's simple imperative syntax, along with its simple LL1 parser, mean that a better syntax for if-expressions and lambda-expressions is basically impossible. Guido likes it this way, and I think he's right.


Input:
How to empty a list in Python? It seems so "dirty" emptying a list in this way:
while len(alist) > 0 : alist.pop()

Does a clear way exist to do that?

Output:
This actually removes the contents from the list, not replaces the old label with a new empty list
del lst[:]

example:
lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)

For the sake of completeness, slice assignment achieves the same effect:
lst[:] = []

and can be used to shrink a part of the list while replacing a part at the same time (but is out of scope of the question).
Note that doing lst = [] does not empty the list, just creates a new object and binds it to the variable lst, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.


Input:
Remove specific characters from a string in python I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string.
for char in line:
    if char in " ?.!/;:":
        line.replace(char,'')

How do I do this properly?

Output:
Strings in Python are immutable (can't be changed).  Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one.  You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed.
Also, the way you are doing it is going to be kind of slow, relatively.  It's also likely to be a bit confusing to experienced pythonators, who will see a doubly-nested structure and think for a moment that something more complicated is going on.
Starting in Python 2.6 and newer Python 2.x versions *, you can instead use str.translate, (but read on for Python 3 differences):
line = line.translate(None, '!@#$')

or regular expression replacement with re.sub
import re
line = re.sub('[!@#$]', '', line)

The characters enclosed in brackets constitute a character class.  Any characters in line which are in that class are replaced with the second parameter to sub: an empty string.
In Python 3, strings are Unicode. You'll have to translate a little differently. kevpie mentions this in a comment on one of the answers, and it's noted in the documentation for str.translate.
When calling the translate method of a Unicode string, you cannot pass the second parameter that we used above. You also can't pass None as the first parameter, or even a translation table from string.maketrans. Instead, you pass a dictionary as the only parameter. This dictionary maps the ordinal values of characters (i.e. the result of calling ord on them) to the ordinal values of the characters which should replace them, orâusefully to usâNone to indicate that they should be deleted.
So to do the above dance with a Unicode string you would call something like
translation_table = dict.fromkeys(map(ord, '!@#$'), None)
unicode_line = unicode_line.translate(translation_table)

Here dict.fromkeys and map are used to succinctly generate a dictionary containing
{ord('!'): None, ord('@'): None, ...}

Even simpler, as another answer puts it, create the dictionary in place:
unicode_line = unicode_line.translate({ord(c): None for c in '!@#$'})

*   for compatibility with earlier Pythons, you can create a "null" translation table to pass in place of None:
import string
line = line.translate(string.maketrans('', ''), '!@#$')

Here string.maketrans is used to create a translation table, which is just a string containing the characters with ordinal values 0 to 255.


Input: What is memoization and how can I use it in Python? I just started Python and I've got no idea what memoization is and how to use it. Also, may I have a simplified example?

Output:
Memoization effectively refers to remembering ("memoization" -> "memorandum" -> to be remembered) results of method calls based on the method inputs and then returning the remembered result rather than computing the result again. You can think of it as a cache for method results. For further details, see page 387 for the definition in Introduction To Algorithms (3e), Cormen et al.
A simple example for computing factorials using memoization in Python would be something like this:
factorial_memo = {}
def factorial(k):
    if k < 2: return 1
    if k not in factorial_memo:
        factorial_memo[k] = k * factorial(k-1)
    return factorial_memo[k]

You can get more complicated and encapsulate the memoization process into a class
class Memoize:
    def __init__(self, f):
        self.f = f
        self.memo = {}
    def __call__(self, *args):
        if not args in self.memo:
            self.memo[args] = self.f(*args)
        return self.memo[args]

Then:
def factorial(k):
    if k < 2: return 1
    return k * factorial(k - 1)

factorial = Memoize(factorial)


Input:
How to overcome "datetime.datetime not JSON serializable" in python? I have a basic dict as follows:
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere

When I try to do jsonify(sample) I get:

TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable

What can I do such that my dictionary sample can overcome the error above?
Note: Though it may not be relevant, the dictionaries are generated from the retrieval of records out of mongodb where when I print out str(sample['somedate']), the output is 2012-08-08 21:46:24.862000.

Output:
Building on other answers, a simple solution based on a specific serializer that just converts datetime.datetime objects to strings.
from datetime import datetime

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, datetime):
        serial = obj.isoformat()
        return serial
    raise TypeError ("Type not serializable")

As seen, the code just checks to find out if object is of class datetime.datetime, and then uses .isoformat() to produce a serialized version of it, according to ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is easily decoded by JavaScript). If more complex serialized representations are sought, other code could be used instead of str() (see other answers to this question for examples). The code ends by raising an exception, to deal with the case it is called with a non-serializable type which is not datetime.
This json_serial function can be used as follows:
from datetime import datetime
from json import dumps

print dumps(datetime.now(), default=json_serial)

The details about how the default parameter to json.dumps works can be found in Section Basic Usage of the json module documentation.


Input:
Python Print String To Text File I'm using Python to open a text document:
text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

I want to enter the string called "TotalAmount" into the text document. Can someone please let me know how to do this?

Output:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

If you use a context manager, the file is closed automatically for you
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

If you're using Python2.6 or higher, it's preferred to use str.format()
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

For python2.7 and higher you can use {} instead of {0}
In Python3, there is an optional file parameter to the print function
with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)


Input:
Writing a list to a file with Python Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters?
file.writelines(["%s\n" % item  for item in list])

It seems like there would be a standard way...

Output:
EDIT Adding info from Thomas' comment
Don't forget to open the file first
thefile = open('test.txt', 'w')

I'd use a loop:
for item in thelist:
  thefile.write("%s\n" % item)

or:
for item in thelist:
  print>>thefile, item

If you're keen on a single function call, at least remove the square brackets [] so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.


Input:
Python, extract file name from path, no matter what the os/path format Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me c:
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c

Output:
Actually, there's a function that returns exactly what you want
print os.path.basename(your_path)


Input:
What's the difference between a Python module and a Python package? What's the difference between a Python module and a Python package?
See also: What's the difference between "package" and "module" (for other languages)

Output:
Any Python file is a module, its name being the file's base name without the .py extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.
The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. As an example, consider the xml package in the Python standard library: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file. See what happens when you try to interactively import package/modules:
>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

In Python there also are built-in modules, such as sys, that are written in C, but I don't think you meant to consider those in your question.


Input:
Cannot install Lxml on Mac os x 10.9 I want to install Lxml so I can then install Scrapy.
When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:
In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#include "libxml/xmlversion.h"
         ^
1 error generated.
error: command 'cc' failed with exit status 1

I have tried using brew to install libxml2 and libxslt, both installed fine but I still cannot install lxml.
Last time I was installing I needed to enable the developer tools on Xcode but since its updated to Xcode 5 it doesnt give me that option anymore.
Does anyone know what I need to do?

Output:
You should install or upgrade the commandline tool for xcode.
Try this in a terminal:
xcode-select --install


Input:
Generator Expressions vs. List Comprehension When should you use generator expressions and when should you use list comprehensions in Python?
# Generator expression
(x*2 for x in range(256))

# List comprehension
[x*2 for x in range(256)]

Output:
John's answer is good (that list comprehensions are better when you want to iterate over something multiple times).  However, it's also worth noting that you should use a list if you want to use any of the list methods.  For example, the following code won't work:
def gen():
    return (something for something in get_some_stuff())

print gen()[:2]     # generators don't support indexing or slicing
print [5,6] + gen() # generators can't be added to lists

Basically, use a generator expression if all you're doing is iterating once.  If you want to store and use the generated results, then you're probably better off with a list comprehension.
Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.


Input:
How to calculate the angle between a line and the horizontal axis? In a programming language (Python, C#, etc) I need to determine how to calculate the angle between a line and the horizontal axis?
I think an image describes best what I want:

Given (P1x,P1y) and (P2x,P2y) what is the best way to calculate this angle? The origin is in the topleft and only the positive quadrant is used.

Output:
First find the difference between the start point and the end point.
deltaY = P2_y - P1_y
deltaX = P2_x - P1_x

Then calculate the angle.
angleInDegrees = arctan(deltaY / deltaX) * 180 / PI

If your language includes an atan2 function it becomes the following instead:
angleInDegrees = atan2(deltaY, deltaX) * 180 / PI

An implementation in Python using radians (provided by Eric Leschinski, who edited my answer):
from math import *
def angle_trunc(a):
    while a < 0.0:
        a += pi * 2
    return a

def getAngleBetweenPoints(x_orig, y_orig, x_landmark, y_landmark):
    deltaY = y_landmark - y_orig
    deltaX = x_landmark - x_orig
    return angle_trunc(atan2(deltaY, deltaX))

angle = getAngleBetweenPoints(5, 2, 1,4)
assert angle >= 0, "angle must be >= 0"
angle = getAngleBetweenPoints(1, 1, 2, 1)
assert angle == 0, "expecting angle to be 0"
angle = getAngleBetweenPoints(2, 1, 1, 1)
assert abs(pi - angle) <= 0.01, "expecting angle to be pi, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 3)
assert abs(angle - pi/2) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 0)
assert abs(angle - (pi+pi/2)) <= 0.01, "expecting angle to be pi+pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(1, 1, 2, 2)
assert abs(angle - (pi/4)) <= 0.01, "expecting angle to be pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -2, -2)
assert abs(angle - (pi+pi/4)) <= 0.01, "expecting angle to be pi+pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -1, 2)
assert abs(angle - (pi/2)) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)

All tests pass. See https://en.wikipedia.org/wiki/Unit_circle


Input:
Convert list to tuple in Python I'm trying to convert a list to a tuple.
When I google it, I find a lot of answers similar to:
l = [4,5,6]
tuple(l)

But if I do that I get this error message:

TypeError: 'tuple' object is not callable

How can I fix this problem?

Output:
It should work fine. Don't use tuple, list or other special names as a variable name. It's probably what's causing your problem.
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)


Input: No module named MySQLdb I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.

Output:
You need to use one of the following commands. Which one depends on what OS and software you have and use.

easy_install mysql-python                                   (mix os)
pip install mysql-python                                    (mix os)
apt-get install python-mysqldb                                (Linux Ubuntu, ...)
cd /usr/ports/databases/py-MySQLdb && make install clean    (FreeBSD)
yum install MySQL-python                                    (Linux Fedora, CentOS ...)

For Windows, see this answer: Install mysql-python (Windows)


Input:
Python "extend" for a dictionary Which is the best way to extend a dictionary with another one? For instance:
>>> a = { "a" : 1, "b" : 2 }
>>> b = { "c" : 3, "d" : 4 }
>>> a
{'a': 1, 'b': 2}
>>> b
{'c': 3, 'd': 4}

I'm looking for any operation to obtain this avoiding for loop:
{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 }

I wish to do something like:
a.extend(b)  # This does not work

Output:
a.update(b)

Python Standard Library Documentation


Input:
How to convert strings into integers in Python? I have a tuple of tuples from a MySQL query like this:
T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))

I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:
T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

I tried to achieve it with eval but didn't get any decent result yet.

Output:
int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer:
print int("1") + 1

The above prints 2.
If you know the structure of your list (that it simply contains lists, only one level), you could do this:
T2 = [map(int, x) for x in T1]


Input: How do I sort a list of strings in Python? What is the best way of creating an alphabetically sorted list in Python?

Output:
Basic answer:
mylist = ["b", "C", "A"]
mylist.sort()

This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function:
for x in sorted(mylist):
    print x

However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter key to specify custom sorting order (the alternative, using cmp, is a deprecated solution, as it has to be evaluated multiple times - key is only computed once per element).
So, to sort according to the current locale, taking language-specific rules into account (cmp_to_key is a helper function from functools):
sorted(mylist, key=cmp_to_key(locale.strcoll))

And finally, if you need, you can specify a custom locale for sorting:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
  key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']

Last note: you will see examples of case-insensitive sorting which use the lower() method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:
# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)


Input:
Chain-calling parent constructors in python Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code.
class A(object):
    def __init__(self):
        print "Constructor A was called"

class B(A):
    def __init__(self):
        super(B,self).__init__()
        print "Constructor B was called"

class C(B):
    def __init__(self):
        super(C,self).__init__()
        print "Constructor C was called"

c = C()

This is how I do it now. But it still seems a bit too non-generic - you still must pass a correct type by hand.
Now, I've tried using self.__class__ as a first argument to super(), but, obviously it doesn't work - if you put it in the constructor for C - fair enough, B's constructor gets called. If you do the same in B, "self" still points to an instance of C so you end up calling B's constructor again (this ends in an infinite recursion).
There is no need to think about diamond inheritance for now, I am just interested in solving this specific problem.

Output:
The way you are doing it is indeed the recommended one (for Python 2.x).
The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".


Input:
Python: Find in list I have come across this delightful:
item = someSortOfSelection()
if item in myList:
    doMySpecialFunction(item)

but sometimes it does not work with all my items, as if they weren't recognized in the list (when it's a list of string).
is it the most 'pythonic' way of finding an item in a list: if x in l:?

Output:
As for your first question: that code is perfectly fine and should work if item equals one of the elements inside myList. Maybe you try to find a string that does not exactly match one of the items or maybe you are using a float value which suffers from inaccuracy.
As for your second question: There's actually several possible ways if "finding" things in lists.
Checking if something is inside
This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in operator for that:
3 in [1, 2, 3] # => True

Filtering a collection
That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:
matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)

The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to
matches = filter(fulfills_some_condition, lst)

in Python 2. Here you can see higher-order functions at work. In Python 3, filter doesn't return a list, but a generator-like object.
Finding the first occurrence
If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known). You can also use
next(x for x in lst if ...)

which will return the first match or raise a StopIteration if none is found. Alternatively, you can use
next((x for x in lst if ...), [default value])

Finding the location of an item
For lists, there's also the index method that can sometimes be useful if you want to know where a certain element is in the list:
[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError

However, note that if you have duplicates, .index always returns the lowest index:
[1,2,3,2].index(2) # => 1

If there are duplicates and you want all the indexes then you can use enumerate() instead:
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]


Input: Difference between __getattr__ vs __getattribute__ I am trying to understand when to use __getattr__ or __getattribute__.  The documentation mentions __getattribute__ applies to new-style classes. What are new-style classes?

Output:
A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn't found the usual ways.  It's good for implementing a fallback for missing attributes, and is probably the one of two you want.
__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly.  You can end up in infinite recursions very easily.
New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class.  But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.
You almost certainly want __getattr__.


Input:
C-like structures in Python Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
class MyStruct():
    def __init__(self, field1, field2, field3):
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3

Output:
Use a named tuple, which was added to the collections module in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's named tuple recipe if you need to support Python 2.4.
It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:
from collections import namedtuple
MyStruct = namedtuple("MyStruct", "field1 field2 field3")

The newly created type can be used like this:
m = MyStruct("foo", "bar", "baz")

Or you can use named arguments:
m = MyStruct(field1 = "foo", field2 = "bar", field3 = "baz")