Python is a dynamically and strongly typed programming language whose design philosophy emphasizes code readability. Two significantly different versions of Python (2 and 3) are in use. Please mention the version that you are using when asking a question about Python.

learn more… | top users | synonyms (2) | python jobs

1796
votes
15answers
328k views

The Python yield keyword explained

What is the use of the yield keyword in Python? What does it do? For example, I'm trying to understand this code (**): def node._get_child_candidates(self, distance, min_dist, max_dist): if ...
1220
votes
9answers
162k views

What is a metaclass in Python?

I've mastered almost all the Python concepts (well, let's say they're just OO concepts :-)) but this one is tricky. I know it has something to do with introspection but it's still unclear to me. So ...
1011
votes
11answers
222k views

How can I make a chain of function decorators in Python?

How can I make two decorators in Python that would do the following. @makebold @makeitalic def say(): return "Hello" which should return <b><i>Hello</i></b> I'm not ...
697
votes
41answers
143k views

How can I represent an 'enum' in Python?

I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an enum in Python?
673
votes
19answers
182k views

Is there any way to run Python on Android?

I like the Android platform. Actually, with some friends, we even participate to the ADC with the Spoxt project. But Java is not my favourite language at all. We are working on a S60 version and this ...
641
votes
17answers
386k views

How do I check if a file exists using Python?

How do I check if a file exists, using Python, without using a try: statement?
629
votes
26answers
384k views

Calling an external command in Python

How can I call an external command in Python?
625
votes
10answers
140k views

Ternary conditional operator in Python

Does Python have a ternary conditional operator? If not, is it possible to simulate one concisely using other language constructs?
578
votes
19answers
66k views

Python progression path - From apprentice to guru [closed]

I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major ...
505
votes
7answers
482k views

Using global variables in a function other than the one that created them

If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
505
votes
18answers
144k views

How can I merge (union) two Python dictionaries in a single expression?

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of ...
479
votes
19answers
74k views

Single quotes vs. double quotes in Python [closed]

According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?
465
votes
11answers
163k views

Python: How do I pass a variable by reference?

The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' class PassByReference: def ...
460
votes
22answers
257k views

Python: Sort a dictionary by value

I have a dictionary of values read from 2 fields in a database: a string field and a numeric field. The string field is unique so that is the key of the dictionary. I can sort on the keys, but how ...
459
votes
9answers
63k views

What is the difference between @staticmethod and @classmethod in Python?

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
459
votes
18answers
24k views

“Least Astonishment” in Python: The Mutable Default Argument

Anyone tinkering with python long enough has been bitten (or torn to pieces) by the following issue: def foo(a=[]): a.append(5) return a Python novices would expect this function to always ...
441
votes
12answers
194k views

Python: What is the best way to check if a list is empty?

For example, if passed the following: a = [] How do I check to see if a is empty?
426
votes
18answers
25k views

Peak detection in a 2D array

I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions. I made a 2D array of ...
414
votes
8answers
249k views

Python: Best way to create directory if it doesn't exist for file write?

What's the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory? Is there a better way than: Update: Somehow, I missed os.path.exists - ...
399
votes
7answers
65k views

Difference between __str__ and __repr__ in Python

What is the difference between __str__ and __repr__ in Python?
391
votes
15answers
159k views

How to install pip on windows?

What is the up-to-date way to install pip on windows? Edit: The accepted answer uses the oficial method. There is also another way, if you use ActivePython, see Rafe Kettler's answer below: ...
363
votes
4answers
188k views

Understanding Python super() and init methods

Trying to understand super(). From the looks of it, both child classes can be created just fine. Im curious as to what difference there actually is in this code: class Base(object): def ...
357
votes
2answers
24k views

Why does Python code run faster in a function?

def main(): for i in xrange(10**8): pass main() This piece of code in Python runs in real 0m1.841s user 0m1.828s sys 0m0.012s However, if the for loop isn't placed within ...
348
votes
11answers
53k views

Why is reading lines from stdin much slower in C++ than Python?

I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is ...
345
votes
4answers
115k views

Accessing the index in Python for loops

Does anyone know how to access the index itself for a list like this: ints = [8, 23, 45, 12, 78] When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?
340
votes
11answers
256k views

How can I remove (chomp) a newline in Python?

This is one of my most common questions when I am coding Python (I was fed Perl as a baby and am forever trying to get rid of that affliction) and I wanted to put it out there on stack overflow so ...
336
votes
11answers
173k views

Static class variables in Python

Is it possible to have static class variables or methods in python? What syntax is required to do this?
326
votes
20answers
115k views

Print in terminal with colors using Python ?

I want to print in the terminal with colors. How can I do that in Python? Another questions what is the best character thatwhen it is printed it look like a box [brick]? I want to print colored ...
324
votes
6answers
51k views

Why use pip over easy_install?

A tweet reads: Don't use easy_install, unless you like stabbing yourself in the face. Use pip. Why use pip over easy_install? Doesn't the fault lie with PyPI and package authors mostly? If ...
319
votes
23answers
48k views

Does Django Scale?

I'm building a web application with Django. The reasons I chose Django were: I wanted to work with free/open-source tools I like Python and feel it's a "long term" language, whereas regarding Ruby I ...
313
votes
5answers
102k views

Static methods in Python?

Is it possible to have static methods in Python so I can call them without initializing a class, like: ClassName.StaticMethod ( )
305
votes
6answers
175k views

Python join, why is it string.join(list) instead of list.join(string)?

This has always confused me. It seems like this would be nicer: my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" Than this: my_list = ["Hello", "world"] print ...
293
votes
9answers
218k views

Add to a dictionary in Python?

Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method...
290
votes
9answers
219k views

How do you read from stdin in python

I'm trying to do some of the code golf challenges but they all require the input to be taken from stdin and I don't know how to get that in python.
289
votes
17answers
176k views

How do I check if a string is a number in Python?

What is the best possible way to check if a string can be represented as a number in Python? The function I currently have right now is: def is_number(s): try: float(s) return ...
287
votes
2answers
235k views

Get the size of a list in python?

items = [] items.append("apple") items.append("orange") items.append("banana") // FAKE METHOD:: items.amount() // should return 3 How I do it right?
277
votes
16answers
245k views

python: import a module from a folder

How do I import a python module given its relative path? For example, if dirFoo contains Foo.py and dirBar, and dirBar contains Bar.py, how do I import Bar.py into Foo.py? Here's a visual ...
275
votes
23answers
83k views

How do you split a list into evenly sized chunks in Python?

I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second ...
274
votes
15answers
99k views

The Python Slice Notation

Do you have a good reference on the Python slice notation? To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head round it and am looking for a ...
268
votes
12answers
387k views

Parse String to Float or Int

In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 542.2222 or "31" to an integer, 31? I just want to know how to parse a float string to a float, and ...
266
votes
12answers
114k views

How do I remove packages installed with Python's easy_install?

Python's easy_install makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing ...
261
votes
7answers
60k views

Which Python memory profiler is recommended?

I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory. Google search shows a commercial one is Python ...
258
votes
14answers
62k views

Pros/Cons of Django vs Pylons [closed]

I'm begining a new webapp in Python. I've narrowed my choices down to Django and Pylons. What are the pros/cons of each?
255
votes
23answers
140k views

Is Python any good for GUI development? [closed]

I am considering creating a GUI-based tool that I want to be cross-platform. I've dismissed Java, as I personally do not like Swing. I'm currently considering C# and using Mono to make it ...
251
votes
11answers
97k views

In Python how do I sort a list of dictionaries by values of the dictionary?

I got a list of dictionaries and want that to be sorted by a value of that dictionary. This [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] sorted by name, should become [{'name':'Bart', ...
249
votes
5answers
171k views

Does python have a string contains method?

I'm looking for a string.contains or string.indexof method in Python. I want to do: if not somestring.contains("blah"): continue
247
votes
8answers
174k views

How to get current time in Python

Can anybody tell what is the module/method used to get current time?
245
votes
1answer
26k views

Catch multiple exceptions in one line (except block)

I know that I can do: try: # do something that may fail except: # do this if ANYTHING goes wrong I can also do this: try: # do something that may fail except ...
244
votes
12answers
52k views

Why are scripting languages (e.g. Perl, Python, Ruby) not suitable as shell languages? [closed]

What are the differences between shell languages like bash, zsh, fish and the scripting languages above that makes them more suitable for the shell? When using the command line the shell languages ...
243
votes
8answers
107k views

What does <if __name__==“__main__”:> do?

Kinda in relation to this question... what does the if __name__=="__main__": part do? # Threading example import time, thread def myfunction(string,sleeptime,lock,*args): while 1: ...

1 2 3 4 5 4079