Input:
Split string on whitespace in Python I'm looking for the Python equivalent of
String str = "many   fancy word \nhello    \thi";
String whiteSpaceRegex = "\\s";
String[] words = str.split(whiteSpaceRegex);

["many", "fancy", "word", "hello", "hi"]

Output:
The str.split() method without an argument splits on whitespace:
>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']


Input:
Get HTML Source of WebElement in Selenium WebDriver using Python I'm using the Python bindings to run Selenium WebDriver.
from selenium import webdriver
wd = webdriver.Firefox()

I know I can grab a webelement like so...
elem = wd.find_element_by_css_selector('#my-id')

And I know I can get the full page source with...
wd.page_source

But is there anyway to get the "element source"?
elem.source   # <-- returns the HTML as a string

The selenium webdriver docs for Python are basically non-existent and I don't see anything in the code that seems to enable that functionality.
Any thoughts on the best way to access the HTML of an element (and its children)?

Output:
You can read innerHTML attribute to get source of the content of the element or outerHTML for source with the current element.
Python:
element.get_attribute('innerHTML')

Java:
elem.getAttribute("innerHTML");

C#:
element.GetAttribute("innerHTML");

Ruby:
element.attribute("innerHTML")

Tested and works with the ChromeDriver.


Input: Get current time in milliseconds in Python? How can I get the current time in milliseconds in Python?

Output:
For what I needed, here's what I did, based on @samplebias' comment above:
import time
millis = int(round(time.time() * 1000))
print millis

Quick'n'easy. Thanks all, sorry for the brain fart.
For reuse:
import time

current_milli_time = lambda: int(round(time.time() * 1000))

Then:
>>> current_milli_time()
1378761833768


Input:
How can I make sense of the `else` statement in Python loops? Many Python programmers are probably unaware that the syntax of while loops and for loops includes an optional else: clause:
for val in iterable:
    do_something(val)
else:
    clean_up()

The body of the else clause is a good place for certain kinds of clean-up actions, and is executed on normal termination of the loop: I.e., exiting the loop with return or break skips the else clause; exiting after a continue executes it. I know this only because I just looked it up (yet again), because  I can never remember when the else clause is executed.
Always? On "failure" of the loop, as the name suggests? On regular termination? Even if the loop is exited with return? I can never be entirely sure without looking it up.
I blame my persisting uncertainty on the choice of keyword: I find else incredibly unmnemonic for this semantics. My question is not "why is this keyword used for this purpose" (which I would probably vote to close, though only after reading the answers and comments), but how can I think about the else keyword so that its semantics make sense, and I can therefore remember it?
I'm sure there was a fair amount of discussion about this, and I can imagine that the choice was made for consistency with the try statement's else: clause (which I also have to look up), and with the goal of not adding to the list of Python's reserved words. Perhaps the reasons for choosing else will clarify its function and make it more memorable, but I'm after connecting name to function, not after historical explanation per se.
The answers to this question, which my question was briefly closed as a duplicate of, contain a lot of interesting back story. My question has a different focus (how to connect the specific semantics of else with the keyword choice), but I feel there should be a link to this question somewhere.

Output:
(This is inspired by @Mark Tolonen's answer.)
An if statement runs its else clause if its condition evaluates to false.
Identically, a while loop runs the else clause if its condition evaluates to false.
This rule matches the behavior you described:

In normal execution, the while loop repeatedly runs until the condition evaluates to false, and therefore naturally exiting the loop runs the else clause.
When you execute a break statement, you exit out of the loop without evaluating the condition, so the condition cannot evaluate to false and you never run the else clause.
When you execute a continue statement, you evaluate the condition again, and do exactly what you normally would at the beginning of a loop iteration.
So, if the condition is true, you keep looping, but if it is false you run the else clause.
Other methods of exiting the loop, such as return, do not evaluate the condition and therefore do not run the else clause.

for loops behave the same way. Just consider the condition as true if the iterator has more elements, or false otherwise.


Input:
Relationship between scipy and numpy scipy appears to provide most (but not all [1]) of numpy's functions in its own namespace. In other words, if there's a function named numpy.foo, there's almost certainly a scipy.foo. Most of the time, the two appear to be exactly the same, oftentimes even pointing to the same function object.
Sometimes, they're different. To give an example that came up recently:

numpy.log10 is a ufunc that returns NaNs for negative arguments;
scipy.log10 returns complex values for negative arguments, and doesn't appear to be a ufunc.

The same can be said about log, log2 and logn, but not about log1p [2].
On the other hand, numpy.exp and scipy.exp appear to be different names for the same ufunc. This is also true of scipy.log1p and numpy.log1p.
Another example is numpy.linalg.solve vs scipy.linalg.solve. They're similar, but the latter offers some additional features over the former.
Why the apparent duplication? If this is meant to be a wholesale import of numpy into the scipy namespace, why the subtle differences in behaviour and the missing functions? Is there some overarching logic that would help clear up the confusion?
[1] numpy.min, numpy.max, numpy.abs and a few others have no counterparts in the scipy namespace.
[2] Tested using numpy 1.5.1 and scipy 0.9.0rc2.

Output:
Last time I checked it, the scipy __init__ method executes a
from numpy import *

so that the whole numpy namespace is included into scipy when the scipy module is imported.
The log10 behaviour you are describing is interesting, because both versions are coming from numpy. One is a ufunc, the other is a numpy.lib function. Why scipy is preferring the library function over the ufunc, I don't know off the top of my head.

EDIT: In fact, I can answer the log10 question. Looking in the scipy __init__ method I see this:
# Import numpy symbols to scipy name space
import numpy as _num
from numpy import oldnumeric
from numpy import *
from numpy.random import rand, randn
from numpy.fft import fft, ifft
from numpy.lib.scimath import *

The log10 function you get in scipy comes from numpy.lib.scimath. Looking at that code, it says:
"""
Wrapper functions to more user-friendly calling of certain math functions
whose output data-type is different than the input data-type in certain
domains of the input.

For example, for functions like log() with branch cuts, the versions in this
module provide the mathematically valid answers in the complex plane:

>>> import math
>>> from numpy.lib import scimath
>>> scimath.log(-math.exp(1)) == (1+1j*math.pi)
True

Similarly, sqrt(), other base logarithms, power() and trig functions are
correctly handled.  See their respective docstrings for specific examples.
"""

It seems that module overlays the base numpy ufuncs for sqrt, log, log2, logn, log10, power, arccos, arcsin, and arctanh. That explains the behaviour you are seeing. The underlying design reason why it is done like that is probably buried in a mailing list post somewhere.


Input:
How to split a string into array of characters with Python? I've tried to look around the web for answers to splitting a string into an array of characters but I can't seem to find a simple method
str.split(//) does not seem to work like Ruby does. Is there a simple way of doing this without looping?

Output:
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']

You need list


Input: Dump a NumPy array into a csv file Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format.

Output:
numpy.savetxt saves an array to a text file.
import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")


Input:
Change one character in a string in Python? What is the easiest way in Python to replace a character in a string like:
text = "abcdefg";
text[1] = "Z";
           ^

Output:
Don't modify strings.
Work with them as lists; turn them into strings only when needed.
>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'

Python strings are immutable (i.e. they can't be modified).  There are a lot of reasons for this.  Use lists until you have no choice, only then turn them into strings.


Input:
Iterating through a range of dates in Python I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension.
day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:
    print strftime("%Y-%m-%d", single_date.timetuple())

Notes

I'm not actually using this to print. That's just for demo purposes.
The start_date and end_date variables are datetime.date objects because I don't need the timestamps. (They're going to be used to generate a report).

Sample Output
For a start date of 2009-05-30 and an end date of 2009-06-09:
2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09

Output:
Why are there two nested iterations? For me it produces the same list of data with only one iteration:
for single_date in (start_date + timedelta(n) for n in range(day_count)):
    print ...

And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.
After all, a linear sequence should only require one iterator, not two.
Update after discussion with John Machin:
Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates:
from datetime import timedelta, date

def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)

start_date = date(2013, 1, 1)
end_date = date(2015, 6, 2)
for single_date in daterange(start_date, end_date):
    print single_date.strftime("%Y-%m-%d")

NB: For consistency with the built-in range() function this iteration stops before reaching the end_date. So for inclusive iteration use the next day, as you would with range().


Input:
How to set environment variables in Python I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variables set. The value is a number.
If I do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be string.
I also want to know how to read the environment variables in python (in the later part of the script) once I set it.

Output:
Environment variables must be strings, so use
os.environ["DEBUSSY"] = "1"

to set the variable DEBUSSY to the string 1.  To access this variable later, simply use
print os.environ["DEBUSSY"]

Child processes automatically inherit the environment of the parent process -- no special action on your part is required.


Input:
Python String and Integer concatenation I want to create string using integer appended to it, in a for loop.  Like this:
for i in range [1,10]:
  string="string"+i

But it returns an error:
TypeError: unsupported operand type(s) for +: 'int' and 'str'

What's the best way to concatenate the String and Integer?

Output:
for i in range (1,10):
    string="string"+str(i)

To get string0, string1 ..... string10, you could do like
>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']


Input:
How do I update pip itself from inside my virtual environment? I'm able to update pip-managed packages, but how do I update pip itself? According to pip --version, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version.
What's the command for that? Do I need to use distribute or is there a native pip or virtualenv command? I've already tried pip update and pip update pip with no success.

Output:
pip is just a PyPI package like any other; you could use it to upgrade itself the same way you would upgrade any package:
pip install --upgrade pip

On Windows the recommended command is:
python -m pip install --upgrade pip


Input:
How can I create a directly-executable cross-platform GUI app using Python? Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.
The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?

Output:
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.
Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)
Of course, there are many, but the most popular that I've seen in wild are:

Tkinter  - based on Tk GUI toolkit (de-facto standard GUI library for python, free for commercial projects)
WxPython - based on WxWidgets (very popular, free for commercial projects)
PyQt - based on Qt (also very popular and more stable than WxWidgets but costly license for commercial projects)

Complete list is at http://wiki.python.org/moin/GuiProgramming
Single executable (Windows)

py2exe - Probably the most popular out there (PyInstaller is also gaining in popularity)

Single executable (Linux)

Freeze - works the same way like py2exe but targets Linux platform

Single executable (Mac)

py2app - again, works like py2exe but targets Mac OS


Input:
Delete Folder Contents in Python How can I delete the contents of a local folder in Python?
The current project is for Windows but I would like to see *nix also.

Output:
Updated to only delete files and to used the os.path.join() method suggested in the comments. If you also want to remove subdirectories, uncomment the elif statement.
import os, shutil
folder = '/path/to/folder'
for the_file in os.listdir(folder):
    file_path = os.path.join(folder, the_file)
    try:
        if os.path.isfile(file_path):
            os.unlink(file_path)
        #elif os.path.isdir(file_path): shutil.rmtree(file_path)
    except Exception as e:
        print(e)


Input:
Get list from pandas DataFrame column headers I want to get a list of the column headers from a pandas DataFrame.  The DataFrame will come from user input so I won't know how many columns there will be or what they will be called.
For example, if I'm given a DataFrame like this:
>>> my_dataframe
    y  gdp  cap
0   1    2    5
1   2    3    9
2   8    7    2
3   3    4    7
4   6    7    7
5   4    8    3
6   8    2    8
7   9    9   10
8   6    6    4
9  10   10    7

I would want to get a list like this:
>>> header_list
[y, gdp, cap]

Output:
You can get the values as a list by doing:
list(my_dataframe.columns.values)


Input:
SSL InsecurePlatform error when using Requests package Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy.
I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with Requests I get an InsecurePlatform exception.
The error mentions urllib3, but I don't have that installed. I did install it to check if it resolved the error, but it didn't.
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3
/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not
available. This prevents urllib3 from configuring SSL appropriately and
may cause certain SSL connections to fail. For more information, see
https://urllib3.readthedocs.org/en/latest
/security.html#insecureplatformwarning.

Any ideas as to why I'm getting this? I've checked the docs, as specified in the error message, but the docs are saying to import urllib3 and either disable the warning, or provide a certificate.

Output:
Use the somewhat hidden security feature:
pip install 'requests[security]'
or
pip install pyOpenSSL ndg-httpsclient pyasn1
Both commands install following extra packages:

pyOpenSSL
ndg-httpsclient
pyasn1

Please note that this is not required for python-2.7.9+.
If pip install fails with errors, check whether you have required development packages for libffi, libssl and python installed in your system using distribution's package manager:

Debian/Ubuntu - python-dev libffi-dev libssl-dev packages.
Fedora - openssl-devel python-devel libffi-devel packages.

Distro list above is incomplete.
Workaround (see the original answer by @TomDotTom):
In case you cannot install some of the required development packages, there's also an option to disable that warning:
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()


Input:
Read .mat files in Python Does anyone have successful experience reading binary Matlab .mat files in Python?
(I've seen that scipy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed scipy version 0.7.0, and I can't find the loadmat() method)

Output:
Silly me. Forgot to import io...
import scipy.io
mat = scipy.io.loadmat('file.mat')


Input:
How can I get a list of all classes within current module in Python? I've seen plenty of examples of people extracting all of the classes from a module, usually something like:
# foo.py
class Foo:
    pass

# test.py
import inspect
import foo

for name, obj in inspect.getmembers(foo):
    if inspect.isclass(obj):
        print obj

Awesome.
But I can't find out how to get all of the classes from the current module.
# foo.py
import inspect

class Foo:
    pass

def print_classes():
    for name, obj in inspect.getmembers(???): # what do I do here?
        if inspect.isclass(obj):
            print obj

# test.py
import foo

foo.print_classes()

This is probably something really obvious, but I haven't been able to find anything. Can anyone help me out?

Output:
Try this:
import sys
current_module = sys.modules[__name__]

In your context:
import sys, inspect
def print_classes():
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj):
            print(obj)

And even better:
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)

Because inspect.getmembers() takes a predicate.


Input:
Python try...except comma vs 'as' in except What is the difference between ',' and 'as' in except statements, eg:
try:
    pass
except Exception, exception:
    pass

and:
try:
    pass
except Exception as exception:
    pass

Is the second syntax legal in 2.6?  It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that it is invalid.
If they are both valid in 2.6 which should I use?

Output:
The definitive document is PEP-3110: Catching Exceptions
Summary:

In Python 3.x, using as is required.
In Python 2.6+, use the as syntax, since it is far less ambiguous and forward compatible with Python 3.x.
In Python 2.5 and earlier, use the comma version, since as isn't supported.


Input:
Search and replace a line in a file in Python I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.
What is the best way to do this, within the following code?
f = open(file)
for line in f:
    if line.contains('foo'):
        newline = line.replace('foo', 'bar')
        # how to write this newline back to the file

Output:
The shortest way would probably be to use the fileinput module. For example, the following adds line numbers to a file, in-place:
import fileinput

for line in fileinput.input("test.txt", inplace=True):
    print "%d: %s" % (fileinput.filelineno(), line),

What happens here is:

The original file is moved to a backup file
The standard output is redirected to the original file within the loop
Thus any print statements write back into the original file

fileinput has more bells and whistles. For example, it can be used to automatically operate on all files in sys.args[1:], without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a with statement.

While fileinput is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable.
There are two options:

The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back.
The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage.


Input:
What is a "callable" in Python? Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.
Could you give me some explanations, including examples with the magic method ?

Output:
A callable is anything that can be called.
The built-in callable (PyCallable_Check in objects.c) checks if the argument is either:

an instance of a class with a __call__ method or
is of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.)

The method named __call__ is (according to the documentation)

Called when the instance is ''called'' as a function

Example
class Foo:
  def __call__(self):
    print 'called'

foo_instance = Foo()
foo_instance() #this is calling the __call__ method


Input:
Best way to convert string to bytes in Python 3? There appears to be two different ways to convert a string to bytes, as seen in the answers to TypeError: 'str' does not support the buffer interface
Which of these methods would be better or more Pythonic? Or is it just a matter of personal preference?
b = bytes(mystring, 'utf-8')

b = mystring.encode('utf-8')

Output:
If you look at the docs for bytes, it points you to bytearray:

bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.
The optional source parameter can be used to initialize the array in a few different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.

So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.
For  encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor.
Edit: I checked the Python source. If you pass a unicode string to bytes using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode; so you're just skipping a level of indirection if you call encode yourself.
Also, see Serdalis' comment -- unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding) and symmetry is nice.


Input:
Python unittest - opposite of assertRaises? I want to write a test to establish that an Exception is not raised in a given circumstance.
It's straightforward to test if an Exception is raised ...
sInvalidPath=AlwaysSuppliesAnInvalidPath()
self.assertRaises(PathIsNotAValidOne, MyObject, sInvalidPath)

... but how can you do the opposite.
Something like this i what I'm after ...
sValidPath=AlwaysSuppliesAValidPath()
self.assertNotRaises(PathIsNotAValidOne, MyObject, sValidPath)

Output:
try:
    myFunc()
except ExceptionType:
    self.fail("myFunc() raised ExceptionType unexpectedly!")


Input:
Most pythonic way to delete a file which may not exist I want to delete the file filename if it exists.  Is it proper to say
if os.path.exists(filename):
    os.remove(filename)

Is there a better way? A one-line way?

Output:
A more pythonic way would be:
try:
    os.remove(filename)
except OSError:
    pass

Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists() and follows the python convention of overusing exceptions.
It may be worthwhile to write a function to do this for you:
import os, errno

def silentremove(filename):
    try:
        os.remove(filename)
    except OSError as e: # this would be "except OSError, e:" before Python 2.6
        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
            raise # re-raise exception if a different error occured


Input:
How to clear python interpreter console? Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times.  I'm wondering if, and how, to clear the Python interpreter console.
I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.
Note: I'm running on Windows, so Ctrl+L doesn't work.

Output:
As you mentioned, you can do a system call:
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()

I am not sure of any other way in Windows.


Input:
How do I keep Python print from adding newlines or spaces? In python, if I say
print 'h'

I get the letter h and a newline.  If I say
print 'h',

I get the letter h and no newline.  If I say
print 'h',
print 'm',

I get the letter h, a space, and the letter m.  How can I prevent Python from printing the space?
The print statements are different iterations of the same loop so I can't just use the + operator.

Output:
Just a comment. In Python 3, you will use
print('h', end='')

to suppress the endline terminator, and
print('a', 'b', 'c', sep='')

to suppress the whitespace separator between items.


Input:
Is there a reason Python strings don't have a string length method? I know that python has a len() function that is used to determine the size of a string, but I was wondering why its not a method of the string object.
Update
Ok, I realized I was embarrassingly mistaken. __len__() is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see __len__ as the name instead of just len.

Output:
Strings do have a length method: __len__()
The protocol in Python is to implement this method on objects which have a length and use the built-in len() function, which calls it for you, similar to the way you would implement __iter__() and use the built-in iter() function (or have the method called behind the scenes for you) on objects which are iterable.
See Emulating container types for more information.
Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment


Input:
Python - The difference between sys.stdout.write and print Are there situations in which sys.stdout.write() is preferable to print?
(Examples: better performance; code that makes more sense)

Output:
print is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file for example:
print >> open('file.txt', 'w'), 'Hello', 'World', 2+3

In Python 3.x, print becomes a function, but it is still possible to pass something else than sys.stdout. See http://docs.python.org/library/functions.html.
In Python 2.6+, print is still a statement, but it can be used as a function with
from __future__ import print_function

Update: There is a little difference between the print function and the print statement (and more generally between a function and a statement) pointed by Bakuriu in comments.
In case of error when evaluating arguments:
print "something", 1/0, "other" #prints only something because 1/0 raise an Exception

print("something", 1/0, "other") #doesn't print anything. The func is not called


Input:
How to change the order of DataFrame columns? I have the following DataFrame (df):
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

I add more column(s) by assignment:
df['mean'] = df.mean(1)

How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?

Output:
One easy way would be to reassign the dataframe with a list of the columns, rearranged as needed.
This is what you have now:
In [6]: df
Out[6]:
          0         1         2         3         4      mean
0  0.445598  0.173835  0.343415  0.682252  0.582616  0.445543
1  0.881592  0.696942  0.702232  0.696724  0.373551  0.670208
2  0.662527  0.955193  0.131016  0.609548  0.804694  0.632596
3  0.260919  0.783467  0.593433  0.033426  0.512019  0.436653
4  0.131842  0.799367  0.182828  0.683330  0.019485  0.363371
5  0.498784  0.873495  0.383811  0.699289  0.480447  0.587165
6  0.388771  0.395757  0.745237  0.628406  0.784473  0.588529
7  0.147986  0.459451  0.310961  0.706435  0.100914  0.345149
8  0.394947  0.863494  0.585030  0.565944  0.356561  0.553195
9  0.689260  0.865243  0.136481  0.386582  0.730399  0.561593

In [7]: cols = df.columns.tolist()

In [8]: cols
Out[8]: [0L, 1L, 2L, 3L, 4L, 'mean']

Rearrange cols in any way you want. This is how I moved the last element to the first position:
In [12]: cols = cols[-1:] + cols[:-1]

In [13]: cols
Out[13]: ['mean', 0L, 1L, 2L, 3L, 4L]

Then reorder the dataframe like this:
In [16]: df = df[cols]  #    OR    df = df.ix[:, cols]

In [17]: df
Out[17]:
       mean         0         1         2         3         4
0  0.445543  0.445598  0.173835  0.343415  0.682252  0.582616
1  0.670208  0.881592  0.696942  0.702232  0.696724  0.373551
2  0.632596  0.662527  0.955193  0.131016  0.609548  0.804694
3  0.436653  0.260919  0.783467  0.593433  0.033426  0.512019
4  0.363371  0.131842  0.799367  0.182828  0.683330  0.019485
5  0.587165  0.498784  0.873495  0.383811  0.699289  0.480447
6  0.588529  0.388771  0.395757  0.745237  0.628406  0.784473
7  0.345149  0.147986  0.459451  0.310961  0.706435  0.100914
8  0.553195  0.394947  0.863494  0.585030  0.565944  0.356561
9  0.561593  0.689260  0.865243  0.136481  0.386582  0.730399


Input:
How can I compare two lists in python and return matches I want to take two lists and find the values that appear in both.
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]

returnMatches(a, b)

would return [5], for instance.

Output:
Not the most efficient one, but by far the most obvious way to do it is:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}

if order is significant you can do it with list comprehensions like this:
>>> [i for i, j in zip(a, b) if i == j]
[5]

(only works for equal-sized lists, which order-significance implies).


Input:
Post JSON using Python Requests I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request".
Here is my client code:
data = {'sender':   'Alice',
    'receiver': 'Bob',
    'message':  'We did it!'}
data_json = simplejson.dumps(data)
payload = {'json_payload': data_json}
r = requests.post("http://localhost:8080", data=payload)

Here is the server code.
class Root(object):

    def __init__(self, content):
        self.content = content
        print self.content  # this works

    exposed = True

    def GET(self):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return simplejson.dumps(self.content)

    def POST(self):
        self.content = simplejson.loads(cherrypy.request.body.read())

Any ideas?

Output:
It turns out I was missing the header information. The following works:
url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)


Input:
Select rows from a DataFrame based on values in a column in pandas How to select rows from a DataFrame based on values in some column in pandas?
In SQL I would use:
select * from table where colume_name = some_value.

I tried to look at pandas documentation but did not immediately find the answer.

Output:
To select rows whose column value equals a scalar, some_value, use ==:
df.loc[df['column_name'] == some_value]

To select rows whose column value is in an iterable, some_values, use isin:
df.loc[df['column_name'].isin(some_values)]

To select rows whose column value does not equal some_value, use !=:
df.loc[df['column_name'] != some_value]

isin returns a boolean Series, so to select rows whose value is not in some_values, negate the boolean Series using ~:
df.loc[~df['column_name'].isin(some_values)]

For example,
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
#      A      B  C   D
# 0  foo    one  0   0
# 1  bar    one  1   2
# 2  foo    two  2   4
# 3  bar  three  3   6
# 4  foo    two  4   8
# 5  bar    two  5  10
# 6  foo    one  6  12
# 7  foo  three  7  14

print(df.loc[df['A'] == 'foo'])

yields
     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

If you have multiple values you want to include, put them in a
list (or more generally, any iterable) and use isin:
print(df.loc[df['B'].isin(['one','three'])])

yields
     A      B  C   D
0  foo    one  0   0
1  bar    one  1   2
3  bar  three  3   6
6  foo    one  6  12
7  foo  three  7  14

Note, however, that if you wish to do this many times, it is more efficient to
make an index first, and then use df.loc:
df = df.set_index(['B'])
print(df.loc['one'])

yields
       A  C   D
B
one  foo  0   0
one  bar  1   2
one  foo  6  12

or, to include multiple values from the index use df.index.isin:
df.loc[df.index.isin(['one','two'])]

yields
       A  C   D
B
one  foo  0   0
one  bar  1   2
two  foo  2   4
two  foo  4   8
two  bar  5  10
one  foo  6  12


Input:
Find all occurrences of a substring in Python Python has string.find() and string.rfind() to get the index of a substring in string.
I wonder, maybe there is something like string.find_all() which can return all founded indexes (not only first from beginning or first from end)?
For example:
string = "test test test test"

print string.find('test') # 0
print string.rfind('test') # 15

#that's the goal
print string.find_all('test') # [0,5,10,15]

Output:
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
>>> [m.start() for m in re.finditer('test', 'test test test test')]
[0, 5, 10, 15]

If you want to find overlapping matches, lookahead will do that:
>>> [m.start() for m in re.finditer('(?=tt)', 'ttt')]
[0, 1]

If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:
>>> search = 'tt'
>>> [m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
[1]

re.finditer returns a generator, so you could change the [] in the above to () to get a generator instead of a list which will be more efficient if you're only iterating through the results once.


Input:
Checking whether a string starts with XXXX I would like to know how to check whether a string starts with "hello" in Python.
In Bash I usually do:
if [[ "$string" =~ ^hello ]]; then
 do something here
fi

How do I achieve the same in Python?

Output:
aString = "hello world"
aString.startswith("hello")


Input:
Remove all occurrences of a value from a Python list In Python remove() will remove the first occurrence of value in a list.
How to remove all occurrences of a value from a list, without sorting the list?
This is what I have in mind.
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> def remove_values_from_list(the_list, val):
        while val in the_list:
            the_list.remove(val)
>>> remove_values_from_list(x, 2)
>>> x
[1, 3, 4, 3]

Output:
Functional approach:
2.x
>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]

3.x
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]


Input:
Python and pip, list all versions of a package that's available? Given the name of a Python (2.X) package that can be installed with pip and virtualenv, is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error.
I'm trying to install a version for a third party library, but the newest version is too new, there were backwards incompatible changes made. So I'd like to somehow have a list of all the versions that pip knows about, so that I can test them.

Output:
Without actually having to download or install any additional packages you can use the syntax for specifying a particular version while not actually specifying any version, and the available versions will be printed:
$ pip install pylibmc==
Collecting pylibmc==
  Could not find a version that satisfies the requirement pylibmc== (from v
  ersions: 0.2, 0.3, 0.4, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.5.5, 0.5, 0.6.1, 0.6,
  0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7, 0.8.1, 0.8.2, 0.8, 0.9.1, 0.9.2, 0.9,
  1.0-alpha, 1.0-beta, 1.0, 1.1.1, 1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0)
No matching distribution found for pylibmc==

update: I had changed my answer to have nothing after the ==, this however doesn't work for older versions of pip (those of you should probably update pip) add any string after the == that is not likely to be an install candidate:
pip install pylibmc==blork


Input:
Strip HTML from strings in Python from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
  print line

When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds 'some text', it will only print 'some text', 'hello' prints 'hello', etc. How would one go about doing this?

Output:
I always used this function to strip HTML tags, as it requires only the Python stdlib:
On Python 2
from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

For Python 3
from html.parser import HTMLParser

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.strict = False
        self.convert_charrefs= True
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

Note: this works only for 3.1. For 3.2 or above, you need to call the parent class's init function. See Using HTMLParser in Python 3.2


Input: Is there any way to do HTTP PUT in python I need to upload some data to a server using HTTP PUT in python. From my brief reading of the urllib2 docs, it only does HTTP POST. Is there any way to do an HTTP PUT in python?

Output:
I've used a variety of python HTTP libs in the past, and I've settled on 'Requests' as my favourite.  Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations.  A basic PUT in requests looks like:
payload = {'username': 'bob', 'email': 'bob@bob.com'}
>>> r = requests.put("http://somedomain.org/endpoint", data=payload)

You can then check the response status code with:
r.status_code

or the response with:
r.content

Requests has a lot synactic sugar and shortcuts that'll make your life easier.


Input:
Python Dictionary Comprehension Is it possible to create a dictionary comprehension in Python (for the keys)?
Without list comprehensions, you can use something like this:
l = []
for n in range(1, 11):
    l.append(n)

We can shorten this to a list comprehension: l = [n for n in range(1, 11)].
However, say I want to set a dictionary's keys to the same value.
I can do:
d = {}
for n in range(1, 11):
     d[n] = True # same value for each

I've tried this:
d = {}
d[i for i in range(1, 11)] = True

However, I get a SyntaxError on the for.
In addition (I don't need this part, but just wondering), can you set a dictionary's keys to a bunch of different values, like this:
d = {}
for n in range(1, 11):
    d[n] = n

Is this possible with a dictionary comprehension?
d = {}
d[i for i in range(1, 11)] = [x for x in range(1, 11)]

This also raises a SyntaxError on the for.

Output:
There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying.  Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary.  Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.
>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

If you want to set them all to True:
>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}

What you seem to be asking for is a way to set multiple keys at once on an existing dictionary.  There's no direct shortcut for that.  You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict.


Input: Does Python support short-circuiting? Does Python support short-circuiting in boolean expressions?

Output: Yep, both and and or operators short-circuit -- see the docs.


Input:
How do you round UP a number in Python? This problem is killing me. How does one roundup a number UP in Python?
I tried round(number) but it round the number down. Example:
round(2.3) = 2.0 and not 3, what I would like

The I tried int(number + .5) but it round the number down again! Example:
int(2.3 + .5) = 2

Then I tried round(number + .5) but it won't work in edge cases. Example:
WAIT! THIS WORKED!

Please advise.

Output:
The ceil (ceiling) function:
import math
print math.ceil(4.2)


Input:
How can I selectively escape percent (%) in Python strings? I have the following code
test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test

print(selectiveEscape)

I would like to get the output:
Print percent % in sentence and not have it break.

What actually happens:
    selectiveEscape = "Use percent % in sentence and not %s" % test
TypeError: %d format: a number is required, not str

Output:
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.


Input:
Passing a dictionary to a function in python as keyword parameters I'd like to call a function in python using a dictionary.
Here is some code:
d = dict(param='test')

def f(param):
    print param

f(d)

This prints {'param': 'test'} but I'd like it to just print test.
I'd like it to work similarly for more parameters:
d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(d)

Is this possible?

Output:
Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary
So my example becomes:
d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)


Input:
Text Progress Bar in the Console Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the console. (Doing a "clear" and then printing the updated percentage.)

Output:
Writing '\r' will move the cursor back to the beginning of the line.
This displays a percentage counter:
import time
import sys

for i in range(100):
    time.sleep(1)
    sys.stdout.write("\r%d%%" % i)
    sys.stdout.flush()


Input:
Is it possible to run a Python script as a service in Windows? If possible, how? I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.
I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.
Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.
Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? Basically, what is the equivalent of putting a start/stop script in /etc/init.d?

Output:
Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).
This is a basic skeleton for a simple service:
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket

class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        self.main()

    def main(self):
        pass

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

Your code would go in the main() method, usually with some kind of infinite loop that might be interrumped by checking a flag, that you set in the SvcStop method


Input: What is the difference between an expression and a statement in Python? In Python, what is the difference between expressions and statements?

Output:
Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any Python object.  Examples:
3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7

Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code.  Note that expressions are statements as well.  Examples:
# all the above expressions
print 42
if x: do_y()
return
a = 7


Input:
Django gives Bad Request (400) when DEBUG = False I am new to django-1.6. When I run the django server with DEBUG = True, it's running perfectly. But when I change DEBUG to False in the settings file, then the server stopped and it gives the following error on the command prompt:
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.

After I changed ALLOWED_HOSTS to ["http://127.0.0.1:8000",], in the browser I get the error:
Bad Request (400)

Is it possible to run Django without debug mode?

Output:
The ALLOWED_HOSTS list should contain fully qualified host names, not urls. Leave out the port and the protocol. If you are using 127.0.0.1, I would add localhost to the list too:
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

You could also use * to match any host:
ALLOWED_HOSTS = ['*']

Quoting the documentation:

Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the requestâs Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE_CLASSES).

Bold emphasis mine.
The status 400 response you get is due to a SuspiciousOperation exception being raised when your host header doesn't match any values in that list.


Input:
listing all functions in a python module I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?
eg. something like:
from somemodule import foo
print foo.methods # or whatever is the correct method to call

Output: You can use dir(module) to see all available methods/attributes.  Also check out PyDocs.


Input:
When is del useful in python? I can't really think of any reason why python needs the del keyword (and most languages seem to not have a similar keyword).  For instance, rather than deleting a variable, one could just assign None to it.  And when deleting from a dictionary, a del method could be added.
Is there any reason to keep del in python, or is it a vestige of Python's pre-garbage collection days?

Output:
Firstly, you can del other things besides local variables
del list_item[4]
del dictionary["alpha"]

Both of which should be clearly useful. Secondly, using del on a local variable makes the intent clearer.  Compare:
   del foo

to
   foo = None

I know in the case of del foo that the intent is to remove the variable from scope. It's not clear that foo = None is doing that. If somebody just assigned foo = None I might think it was dead code. But I instantly know what somebody who codes del foo was trying to do.


Input: Permanently add a directory to PYTHONPATH Whenever I use sys.path.append, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH?

Output:
If you're using bash (on a Mac or GNU/Linux distro), add this to your ~/.bashrc
export PYTHONPATH="${PYTHONPATH}:/my/other/path"


Input:
Seeking clarification on apparent contradictions regarding weakly typed languages I think I understand strong typing, but every time I look for examples for what is weak typing I end up finding examples of programming languages that simply coerce/convert types automatically.
For instance, in this article named Typing: Strong vs. Weak, Static vs. Dynamic says that Python is strongly typed because you get an exception if you try to:
Python
1 + "1"
Traceback (most recent call last):
File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'

However, such thing is possible in Java and in C#, and we do not consider them weakly typed just for that.
Java
  int a = 10;
  String b = "b";
  String result = a + b;
  System.out.println(result);

C#
int a = 10;
string b = "b";
string c = a + b;
Console.WriteLine(c);

In this another article named Weakly Type Languages the author says that Perl is weakly typed simply because I can concatenate a string to a number and viceversa without any explicit conversion.
Perl
$a=10;
$b="a";
$c=$a.$b;
print $c; #10a

So the same example makes Perl weakly typed, but not Java and C#?.
Gee, this is confusing
The authors seem to imply that a language that prevents the application of certain operations on values of different types is strongly typed and the contrary means weakly typed.
Therefore, at some point I have felt prompted to believe that if a language provides a lot of automatic conversions or coercion between types (as perl) may end up being considered weakly typed, whereas other languages that provide only a few conversions may end up being considered strongly typed.
I am inclined to believe, though, that I must be wrong in this interepretation, I just do not know why or how to explain it.
So, my questions are:

What does it really mean for a language to be truly weakly typed?
Could you mention any good examples of weakly typing that are not related to automatic conversion/automatic coercion done by the language?
Can a language be weakly typed and strongly typed at the same time?

Output:
UPDATE: This question was the subject of my blog on the 15th of October, 2012. Thanks for the great question!

What does it really mean for a language to be "weakly typed"?

It means "this language uses a type system that I find distasteful". A "strongly typed" language by contrast is a language with a type system that I find pleasant.
The terms are essentially meaningless and you should avoid them. Wikipedia lists eleven different meanings for "strongly typed", several of which are contradictory. This indicates that the odds of confusion being created are high in any conversation involving the term "strongly typed" or "weakly typed".
All that you can really say with any certainty is that a "strongly typed" language under discussion has some additional restriction in the type system, either at runtime or compile time, that a "weakly typed" language under discussion lacks. What that restriction might be cannot be determined without further context.
Instead of using "strongly typed" and "weakly typed", you should describe in detail what kind of type safety you mean. For example, C# is a statically typed language and a type safe language and a memory safe language, for the most part. C# allows all three of those forms of "strong" typing to be violated.  The cast operator violates static typing; it says to the compiler "I know more about the runtime type of this expression than you do". If the developer is wrong, then the runtime will throw an exception in order to protect type safety. If the developer wishes to break type safety or memory safety, they can do so by turning off the type safety system by making an "unsafe" block. In an unsafe block you can use pointer magic to treat an int as a float (violating type safety) or to write to memory you do not own. (Violating memory safety.)
C# imposes type restrictions that are checked at both compile-time and at runtime, thereby making it a "strongly typed" language compared to languages that do less compile-time checking or less runtime checking. C# also allows you to in special circumstances do an end-run around those restrictions, making it a "weakly typed" language compared with languages which do not allow you to do such an end-run.
Which is it really?  It is impossible to say; it depends on the point of view of the speaker and their attitude towards the various language features.


Input: Web scraping with Python I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?

Output:
Use urllib2 in combination with the brilliant BeautifulSoup library:
import urllib2
from BeautifulSoup import BeautifulSoup
# or if you're using BeautifulSoup4:
# from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://example.com').read())

for row in soup('table', {'class': 'spad'})[0].tbody('tr'):
    tds = row('td')
    print tds[0].string, tds[1].string
    # will print date and sunrise


Input: How to use Xpath in Python? What is the library? Is there a full implementation? How is the library used? Where is its website?

Output:
libxml2 has a number of advantages:

Compliance to the spec
Active development and a community participation
Speed. This is really a python wrapper around a C implementation.
Ubiquity. The libxml2 library is pervasive and thus well tested.

Downsides include:

Compliance to the spec. It's strict. Things like default namespace handling are easier in other libraries.
Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.
Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.

If you are doing simple path selection, stick with ElementTree ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.
Sample of libxml2 XPath Use

import libxml2

doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
    print "xpath query: wrong node set size"
    sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
    print "xpath query: wrong node set value"
    sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()

Sample of ElementTree XPath Use

from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
    print e.get('title').text


Input:
Expanding tuples into arguments Is there a way to expand a Python tuple into a function - as actual parameters?
For example, here expand() does the magic:
tuple = (1, "foo", "bar")

def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)

myfun(expand(tuple)) # (2, "foobar", "barfoo")

I know one could define myfun as myfun((a, b, c)), but of course there may be legacy code.
Thanks

Output:
myfun(*tuple) does exactly what you request.
Side issue: don't use as your identifiers builtin type names such as tuple, list, file, set, and so forth -- it's horrible practice and it will come back and byte you when you least expect it,
so just get into the habit of actively avoiding hiding builtin names with your own identifiers.


Input:
Is there a short contains function for lists? I see people are using any to gather another list to see if an item exists in a list, but is there a quick way to just do?:
if list.contains(myItem):
    # do something

Output:
You can use this syntax:
if myItem in list:
    # do something

Also, inverse operator:
if myItem not in list:
    # do something

It's work fine for lists, tuples, sets and dicts (check keys).
Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.


Input:
Finding the average of a list I have to find the average of a list in Python. This is my code so far
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)

I've got it so it adds together the values in the list, but I don't know how to make it divide into them?

Output:
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(l) / float(len(l))


Input:
Split a string by spaces -- preserving quoted substrings -- in Python I have a string which is like this:
this is "a test"

I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
['this','is','a test']

PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.

Output:
You want split, from the shlex module.
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']

This should do exactly what you want.


Input:
How can I convert a datetime object to milliseconds since epoch (unix time) in Python? I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.
How do I do this?

Output:
It appears to me that the simplest way to do this is
import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0


Input:
How to change the font size on a matplotlib plot How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot?
I know how to change the tick label sizes, this is done with:
import matplotlib
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)

But how does one change the rest?

Output:
From the matplotlib documentation,
font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 22}

matplotlib.rc('font', **font)

This sets the font of all items to the font specified by the kwargs object, font.
Alternatively, you could also use the rcParams update method as suggested in this answer:
matplotlib.rcParams.update({'font.size': 22})

You can find a full list of available properties on the Customizing matplotlib page.


Input:
Check if a given key already exists in a dictionary and increment it Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
my_dict = {}

if (my_dict[key] != None):
  my_dict[key] = 1
else:
  my_dict[key] += 1

I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.

Output:
You are looking for collections.defaultdict (available for Python 2.5+). This
from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

will do what you want.
For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use
if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1


Input:
Does Python SciPy need BLAS? numpy.distutils.system_info.BlasNotFoundError:
    Blas (http://www.netlib.org/blas/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [blas]) or by setting
    the BLAS environment variable.

Which tar do I need to download off this site?
I've tried the fortrans, but I keep getting this error (after setting the environment variable obviously).

Output:
If you need to use the latest versions of SciPy rather than the packaged version, without going through the hassle of building BLAS and LAPACK, you can follow the below procedure.
Install linear algebra libraries from repository (for Ubuntu),
sudo apt-get install gfortran libopenblas-dev liblapack-dev

Then install SciPy, (after downloading the SciPy source): python setup.py install or
pip install scipy

As the case may be.


Input:
Return None if Dictionary key is not available I need a way to get a dictionary value if its key exists, or simply return None, if it does not.
However, Python returns a key_error if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not exist ?

Output:
You can use get()
value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:
value = d.get(key, "empty")


Input:
How to query as GROUP BY in django? I query a model,
Members.objects.all()

and it returns say
Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop

What i want is, to know the best Django way to fire
a group_by query to my db, as like,
Members.objects.all().group_by('designation')

Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.

Output:
If you mean to do aggregation and are using Django 1.1 (currently in alpha 1), you can use the new aggregation features of the ORM:
from django.db.models import Count
Members.objects.values('designation').annotate(dcount=Count('designation'))

This results in a query similar to
SELECT designation, COUNT(designation) AS dcount
FROM members GROUP BY designation

and the output would be of the form
[{'designation': 'Salesman', 'dcount': 2},
 {'designation': 'Manager', 'dcount': 2}]


Input:
Pandas: change data type of columns I want to convert a table, represented as a list of lists, into a Pandas DataFrame. As an extremely simplified example:
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a)

What is the best way to convert the columns to the appropriate types, in this case columns 2 and 3 into floats? Is there a way to specify the types while converting to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the type for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns and I don't want to specify exactly which columns are of which type. All I can guarantee is that each columns contains values of the same type.

Output:
How about this?
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]:
  one  two three
0   a  1.2   4.2
1   b   70  0.03
2   x    5     0

df.dtypes
Out[17]:
one      object
two      object
three    object

df[['two', 'three']] = df[['two', 'three']].astype(float)

df.dtypes
Out[19]:
one       object
two      float64
three    float64


Input:
How do I get list of methods in a Python class? I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?
Also see:

How can I list the methods in a
Python 2.5 module?
Looping over
a Python / IronPython Object
Methods
Finding the methods an
object has
How do I look inside
a Python object?
How Do I
Perform Introspection on an Object in
Python 2.x?
How to get a
complete list of objectâs methods and
attributes?
Finding out which
functions are available from a class
instance in python?

Output:
An example (listing the methods of the optparse.OptionParser class):
>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
 ('add_option', <unbound method OptionParser.add_option>),
 ('add_option_group', <unbound method OptionParser.add_option_group>),
 ('add_options', <unbound method OptionParser.add_options>),
 ('check_values', <unbound method OptionParser.check_values>),
 ('destroy', <unbound method OptionParser.destroy>),
 ('disable_interspersed_args',
  <unbound method OptionParser.disable_interspersed_args>),
 ('enable_interspersed_args',
  <unbound method OptionParser.enable_interspersed_args>),
 ('error', <unbound method OptionParser.error>),
 ('exit', <unbound method OptionParser.exit>),
 ('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
 ...
 ]

Notice that getmembers returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...


Input:
How to use timeit module I understand the concept of what timeit does but I am not sure how to implement it in my code.
How can I compare two functions, say insertion_sort and tim_sort, with timeit?

Output:
If you want to use timeit in an interactive Python session, there are two convenient options:

Use the IPython shell.  It features the convenient %timeit special function:
In [1]: def f(x):
   ...:     return x*x
   ...:

In [2]: %timeit for x in range(100): f(x)
100000 loops, best of 3: 20.3 us per loop

In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__ in the setup statement:
>>> def f(x):
...     return x * x
...
>>> import timeit
>>> timeit.repeat("for x in range(100): f(x)", "from __main__ import f",
                  number=100000)
[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]


Input:
How can I convert a character to a integer in Python, and viceversa? I want to get, given a character, its ASCII value.
For example, for the character a, I want to get 97, and vice versa.

Output:
Use chr() and ord():
>>> chr(97)
'a'
>>> ord('a')
97


Input:
What is the easiest way to remove all packages installed by pip? I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production.
Is there a quick and easy way to do this with pip?

Output:
I've found this snippet as an alternative solution. It's a more graceful removal of libraries than remaking the virtualenv:
pip freeze | xargs pip uninstall -y

In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below):
pip freeze | grep -v "^-e" | xargs pip uninstall -y


Input:
Python pip install fails: invalid command egg_info I find that recently often when I try to install a Python package using pip, I get the error(s) below.
I found a reference online that one has to use "python2 setup.py install" from the download directory, and indeed find that this will then work if I manually find and download the package (from pypi).
But, I don't know where pip is downloading packages to, and/or why it is failing in this manner.
I tried to do a pip upgrade, but it also failed in a similar manner, with a bunch of "Unknown distribution option" errors (entry_points, zip_safe, test_suite, tests_require)!

pip 1.0.1
ActivePython 2.7

Trying to use ActiveState's pypm fails, because they have a smaller library base, and it doesn't include these packages.
C:\test>pip install requests-oauth
Downloading/unpacking requests-oauth
  Downloading requests-oauth-0.4.1.tar.gz
  Running setup.py egg_info for package requests-oauth
    E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'zip_safe'
      warnings.warn(msg)
    E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
      warnings.warn(msg)
    usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
       or: -c --help [cmd1 cmd2 ...]
       or: -c --help-commands
       or: -c cmd --help

    error: invalid command 'egg_info'
    Complete output from command python setup.py egg_info:
    E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'zip_safe'
  warnings.warn(msg)

E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)

usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: -c --help [cmd1 cmd2 ...]
   or: -c --help-commands
   or: -c cmd --help

error: invalid command 'egg_info'

Output:
Install distribute, which comes with egg_info.
Should be as simple as pip install Distribute.
Distribute has been merged into Setuptools as of version 0.7. If you are using a version <=0.6, upgrade using pip install --upgrade setuptools or easy_install -U setuptools.


Input: When is "i += x" different from "i = i + x" in Python? I was told that += can have different effects than the standard notation of i = i +. Is there a case in which i += 1 would be different from i = i + 1?

Output:
This depends entirely on the object i.
+= calls the __iadd__ method (if it exists -- falling back on __add__ if it doesn't exist) whereas + calls the __add__ method1.
From an API perspective, __iadd__ is supposed to be used for modifying mutable objects in place (returning the object which was mutated) whereas __add__ should return a new instance of something.  For immutable objects, both methods return a new instance, but __iadd__ will put the new instance in the current namespace with the same name that the old instance had.  This is why
i = 1
i += 1

seems to increment i.  In reality, you get a new integer and assign it "on top of" i -- losing one reference to the old integer.  In this case, i += 1 is exactly the same as i = i + 1.  But, with most mutable objects, it's a different story:
As a concrete example:
a = [1, 2, 3]
b = a
b += [1, 2, 3]
print a  #[1, 2, 3, 1, 2, 3]
print b  #[1, 2, 3, 1, 2, 3]

compared to:
a = [1, 2, 3]
b = a
b = b + [1, 2, 3]
print a #[1, 2, 3]
print b #[1, 2, 3, 1, 2, 3]

notice how in the first example, since b and a reference the same object, when I use += on b, it actually changes b (and a sees that change too -- After all, it's referencing the same list).  In the second case however, when I do b = b + [1, 2, 3], this takes the list that b is referencing and concatenates it with a new list [1, 2, 3].  It then stores the concatenated list in the current namespace as b -- With no regard for what b was the line before.

1In the expression x + y, if x.__add__ isn't implemented or if x.__add__(y) returns NotImplemented and x and y have different types, then x + y tries to call y.__radd__(x).  So, in the case where you have
foo_instance += bar_instance
if Foo doesn't implement __add__ or __iadd__ then the result here is the same as
foo_instance = bar_instance.__radd__(bar_instance,foo_instance)


Input: How to read csv into record array in numpy? I wonder if there is a direct way to import the contents of a csv file into a record array, much in the way that R's read.table(), read.delim(), and read.csv() family imports data to R's data frame? Or is the best way to use csv.reader() and then apply something like numpy.core.records.fromrecords()?

Output:
You can use Numpy's genfromtxt() method to do so, by setting the delimiter kwarg to a comma.
from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')

More information on the function can be found at its respective documentation.


Input:
Why compile Python code? Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?
I also notice that some files in my application get compiled into .pyc while others do not, why is this?

Output:
It's compiled to bytecode which can be used much, much, much faster.
The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.
Important addition by Ben Blank:

It's worth noting that while running a
  compiled script has a faster startup
  time (as it doesn't need to be
  compiled), it doesn't run any
  faster.


Input:
What are the differences between numpy arrays and matrices? Which one should I use? What are the advantages and disadvantages of each?
From what I've seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them?
Will the style of the program influence my choice? I am doing some machine learning using numpy, so there are indeed lots of matrices, but also lots of vectors (arrays).

Output:
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are
N-dimensional.  Matrix objects are a subclass of ndarray, so they inherit all
the attributes and methods of ndarrays.
The main advantage of numpy matrices is that they provide a convenient notation
for matrix multiplication: if a and b are matrices, then a*b is their matrix
product.
import numpy as np

a=np.mat('4 3; 2 1')
b=np.mat('1 2; 3 4')
print(a)
# [[4 3]
#  [2 1]]
print(b)
# [[1 2]
#  [3 4]]
print(a*b)
# [[13 20]
#  [ 5  8]]

Both matrix objects and ndarrays have .T to return the transpose, but matrix
objects also have .H for the conjugate transpose, and .I for the inverse.
In contrast, numpy arrays consistently abide by the rule that operations are
applied element-wise. Thus, if a and b are numpy arrays, then a*b is the array
formed by multiplying the components element-wise:
c=np.array([[4, 3], [2, 1]])
d=np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
#  [6 4]]

To obtain the result of matrix multiplication, you use np.dot :
print(np.dot(c,d))
# [[13 20]
#  [ 5  8]]

The ** operator also behaves differently:
print(a**2)
# [[22 15]
#  [10  7]]
print(c**2)
# [[16  9]
#  [ 4  1]]

Since a is a matrix, a**2 returns the matrix product a*a.
Since c is an ndarray, c**2 returns an ndarray with each component squared
element-wise.
There are other technical differences between matrix objects and ndarrays
(having to do with np.ravel, item selection and sequence behavior).
The main advantage of numpy arrays is that they are more general than
2-dimensional matrices. What happens when you want a 3-dimensional array? Then
you have to use an ndarray, not a matrix object. Thus, learning to use matrix
objects is more work -- you have to learn matrix object operations, and
ndarray operations.
Writing a program that uses both matrices and arrays makes your life difficult
because you have to keep track of what type of object your variables are, lest
multiplication return something you don't expect.
In contrast, if you stick solely with ndarrays, then you can do everything
matrix objects can do, and more, except with slightly different
functions/notation.
If you are willing to give up the visual appeal of numpy matrix product
notation, then I think numpy arrays are definitely the way to go.
PS. Of course, you really don't have to choose one at the expense of the other,
since np.asmatrix and np.asarray allow you to convert one to the other (as
long as the array is 2-dimensional).


Input:
Implement touch using Python? touch is a Unix utility that sets the modification and access times of files to the current time of day.  If the file doesn't exist, it is created with default permissions.
How would you implement it as a Python function? Try to be cross platform and complete.
(Current Google results for "python touch file" are not that great, but point to os.utime.)

Output:
This tries to be a little more race-free than the other solutions.  (The with keyword is new in Python 2.5.)
import os
def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)

Roughly equivalent to this.
import os
def touch(fname, times=None):
    fhandle = open(fname, 'a')
    try:
        os.utime(fname, times)
    finally:
        fhandle.close()

Now, to really make it race-free, you need to use futimes and change the timestamp of the open filehandle, instead of opening the file and then changing the timestamp on the filename (which may have been renamed).  Unfortunately, Python doesn't seem to provide a way to call futimes without going through ctypes or similar...

EDIT
As noted by Nate Parsons, Python 3.3 will add specifying a file descriptor (when os.supports_fd) to functions such as os.utime, which will use the futimes syscall instead of the utimes syscall under the hood.  In other words:
import os
def touch(fname, mode=0o666, dir_fd=None, **kwargs):
    flags = os.O_CREAT | os.O_APPEND
    with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f:
        os.utime(f.fileno() if os.utime in os.supports_fd else fname,
            dir_fd=None if os.supports_fd else dir_fd, **kwargs)


Input:
Turn a string into a valid filename in Python I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like "_-.() ". What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.

Output:
You can look at the Django framework for how they create a "slug" from arbitrary text.  A slug is URL- and filename- friendly.
Their template/defaultfilters.py (at around line 183) defines a function, slugify, that's probably the gold standard for this kind of thing.  Essentially, their code is the following.
def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    import unicodedata
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
    value = unicode(re.sub('[-\s]+', '-', value))

There's more, but I left it out, since it doesn't address slugification, but escaping.


Input:
How do I set the figure title and axes labels font size in Matplotlib? I am creating a figure in Matplotlib like this:
from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')

I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually?

Output:
Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:
from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page):
axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

(As far as I can see, there is no way to set x and y label sizes separately.)
And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.


Input:
Finding what methods an object has Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?
Or,
if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?

Output:
It appears you can use this code, replacing 'object' with the object you're interested in:-
[method for method in dir(object) if callable(getattr(object, method))]

I discovered it at this site, hopefully that should provide some further detail!


Input:
How do I avoid the "self.x = x; self.y = y; self.z = z" pattern in __init__? I see patterns like
def __init__(self, x, y, z):
    ...
    self.x = x
    self.y = y
    self.z = z
    ...

quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Should I inherit from namedtuple?

Output:
EDIT
It seems that several people are concerned about presenting this solution, so I will provide a very clear disclaimer. You should not use this solution. I only provide it as information, so you know that the language is capable of this. The rest of the answer is just showing language capabilities, not endorsing using them in this way.
ORIGINAL ANSWER
There isn't really anything wrong with explicitly copying parameters into attributes. If you have too many parameters in the ctor, it is sometimes considered a code smell and maybe you should group these params into a fewer objects. Other times, it is necessary and there is nothing wrong with it. Anyway, doing it explicitly is the way to go.
However, since you are asking HOW it can be done (and not whether it should be done), then one solution is this:
class A:
    def __init__(self, **kwargs):
        for key in kwargs:
          setattr(self, key, kwargs[key])

a = A(l=1, d=2)
a.l # will return 1
a.d # will return 2


Input:
Is it a good practice to use try-except-else in Python? From time to time in Python, I see the block:
try:
   try_this(whatever)
except SomeException as exception:
   #Handle exception
else:
   return something

What is the reason for the try-except-else to exist?
I do not like that kind of programming, as it is using exceptions to perform flow control. However, if it is included in the language, there must be a good reason for it, isn't it?
It is my understanding that exceptions are not errors, and that they should only be used for exceptional conditions (e.g. I try to write a file into disk and there is no more space, or maybe I do not have permission), and not for flow control.
Normally I handle exceptions as:
something = some_default_value
try:
    something = try_this(whatever)
except SomeException as exception:
    #Handle exception
finally:
    return something

Or if I really do not want to return anything if an exception happens, then:
try:
    something = try_this(whatever)
    return something
except SomeException as exception:
    #Handle exception

Output:
"I do not know if it is out of ignorance, but i do not like that
  kind of programming, as it is using exceptions to perform flow control."

In the Python world, using exceptions for flow control is common and normal.
Even the Python core developers use exceptions for flow-control and that style is heavily baked into the language (i.e.  the iterator protocol uses StopIteration to signal loop termination).
In addition, the try-except-style is used to prevent the race-conditions inherent in some of the "look-before-you-leap" constructs.   For example, testing os.path.exists results in information that may be out-of-date by the time you use it.  Likewise, Queue.full returns information that may be stale.  The try-except-else style will produce more reliable code in these cases.

"It my understanding that exceptions are not errors, they should only
  be used for exceptional conditions"

In some other languages, that rule reflects their cultural norms as reflected in their libraries.  The "rule" is also based in-part on performance considerations for those languages.
The Python cultural norm is somewhat different.  In many cases, you must use exceptions for control-flow.  Also, the use of exceptions in Python does not slow the surrounding code and calling code as it does in some compiled languages (i.e. CPython already implements code for exception checking at every step, regardless of whether you actually use exceptions or not).
In other words, your understanding that "exceptions are for the exceptional" is a rule that makes sense in some other languages, but not for Python.

"However, if it is included in the language itself, there must be a
  good reason for it, isn't it?"

Besides helping to avoid race-conditions, exceptions are also very useful for pulling error-handling outside loops.   This is a necessary optimization in interpreted languages which do not tend to have automatic loop invariant code motion.
Also, exceptions can simplify code quite a bit in common situations where the ability to handle an issue is far removed from where the issue arose.  For example, it is common to have top level user-interface code calling code for business logic which in turn calls low-level routines.  Situations arising in the low-level routines (such as duplicate records for unique keys in database accesses) can only be handled in top-level code (such as asking the user for a new key that doesn't conflict with existing keys).  The use of exceptions for this kind of control-flow allows the mid-level routines to completely ignore the issue and be nicely decoupled from that aspect of flow-control.
There is a nice blog post on the indispensibility of exceptions here.
Also, see this StackOverFlow answer: Are exceptions really for exceptional errors?

"What is the reason for the try-except-else to exist?"

The else-clause itself is interesting.  It runs when there is no exception but before the finally-clause.  That is its primary purpose.
Without the else-clause, the only option to run additional code before finalization would be the clumsy practice of adding the code to the try-clause.  That is clumsy because it risks
raising exceptions in code that wasn't intended to be protected by the try-block.
The use-case of running additional unprotected code prior to finalization doesn't arise very often.  So, don't expect to see many examples in published code.  It is somewhat rare.
Another use-case for the else-clause is to perform actions that must occur when no exception occurs and that do not occur when exceptions are handled.  For example:
   recip = float('Inf')
   try:
       recip = 1 / f(x)
   except ZeroDivisionError:
       logging.info('Infinite result')
   else:
       logging.info('Finite result')

Lastly, the most common use of an else-clause in a try-block is for a bit of beautification (aligning the exceptional outcomes and non-exceptional outcomes at the same level of indentation).  This use is always optional and isn't strictly necessary.


Input: Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad? I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.

Output:
Python (the language) doesn't need a GIL (which is why it can perfectly be implemented on JVM [Jython] and .NET [IronPython], and those implementations multithread freely). CPython (the popular implementation) has always used a GIL for ease of coding (esp. the coding of the garbage collection mechanisms) and of integration of non-thread-safe C-coded libraries (there used to be a ton of those around;-).
The Unladen Swallow project, among other ambitious goals, does plan a GIL-free virtual machine for Python -- to quote that site, "In addition, we intend to remove the GIL and fix the state of multithreading in Python. We believe this is possible through the implementation of a more sophisticated GC system, something like IBM's Recycler (Bacon et al, 2001)."


Input:
Python mysqldb: Library not loaded: libmysqlclient.18.dylib I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports
import MySQLdb as mysql

Firstly, this command is red underlined and the info tells me "Unresolved import". Then I tried to run the following simple python code
import MySQLdb as mysql

def main():
    conn = mysql.connect( charset="utf8", use_unicode=True, host="localhost",user="root", passwd="",db="" )

if __name__ == '__main__'():
    main()

When executing it I get the following error message
Traceback (most recent call last):
  File "/path/to/project/Python/src/cvdv/TestMySQLdb.py", line 4, in <module>
    import MySQLdb as mysql
  File "build/bdist.macosx-10.6-intel/egg/MySQLdb/__init__.py", line 19, in <module>
    \namespace cvdv
  File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 7, in <module>
  File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so
  Reason: image not found

What might be the solution to my problem?
EDIT:
Actually I found out that the library lies in /usr/local/mysql/lib. So I need to tell my pydev eclipse version where to find it. Where do I set this?

Output:
I solved the problem by creating a symbolic link to the library. I.e.
The actual library resides in
/usr/local/mysql/lib

And then I created a symbolic link in
/usr/lib

Using the command:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

so that I have the following mapping:
ls -l libmysqlclient.18.dylib
lrwxr-xr-x  1 root  wheel  44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib

That was it. After that everything worked fine.
EDIT:
Notice, to do this in El Capitan mac os release, you need disable SIP. Here is hint how do it in final release: http://apple.stackexchange.com/a/208481/90910 .


Input:
How to drop rows of Pandas dataframe whose value of certain column is NaN I have a df :
>>> df
                 STK_ID  EPS  cash
STK_ID RPT_Date
601166 20111231  601166  NaN   NaN
600036 20111231  600036  NaN    12
600016 20111231  600016  4.3   NaN
601009 20111231  601009  NaN   NaN
601939 20111231  601939  2.5   NaN
000001 20111231  000001  NaN   NaN

Then I just want the records whose EPS is not NaN, that is, df.drop(....) will return the dataframe as below:
                  STK_ID  EPS  cash
STK_ID RPT_Date
600016 20111231  600016  4.3   NaN
601939 20111231  601939  2.5   NaN

How to do that ?

Output:
This question is already resolved, but...
...also consider the solution suggested by Wouter in his original comment. The ability to handle missing data, including dropna(), is built into pandas explicitly. Aside from potentially improved performance over doing it manually, these functions also come with a variety of options which may be useful.
In [24]: df = pd.DataFrame(np.random.randn(10,3))

In [25]: df.ix[::2,0] = np.nan; df.ix[::4,1] = np.nan; df.ix[::3,2] = np.nan;

In [26]: df
Out[26]:
          0         1         2
0       NaN       NaN       NaN
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
4       NaN       NaN  0.050742
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
8       NaN       NaN  0.637482
9 -0.310130  0.078891       NaN

In [27]: df.dropna()     #drop all rows that have any NaN values
Out[27]:
          0         1         2
1  2.677677 -1.466923 -0.750366
5 -1.250970  0.030561 -2.678622
7  0.049896 -0.308003  0.823295

In [28]: df.dropna(how='all')     #drop only if ALL columns are NaN
Out[28]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
4       NaN       NaN  0.050742
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
8       NaN       NaN  0.637482
9 -0.310130  0.078891       NaN

In [29]: df.dropna(thresh=2)   #Drop row if it does not have at least two values that are **not** NaN
Out[29]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
5 -1.250970  0.030561 -2.678622
7  0.049896 -0.308003  0.823295
9 -0.310130  0.078891       NaN

In [30]: df.dropna(subset=[1])   #Drop only if NaN in specific column (as asked in the question)
Out[30]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
9 -0.310130  0.078891       NaN

There are also other options (See docs at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html), including dropping columns instead of rows.
Pretty handy!