Questions tagged [python]

519368 questions
8.7k

votes
30

answer
1.9m

Views

What does the “yield” keyword do?

What is the use of the yield keyword in Python? What does it do? For example, I'm trying to understand this code1: def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance + max_di...
Alex. S.
4.9k

votes
30

answer
3.4m

Views

How do I check whether a file exists without exceptions?

How do I see if a file exists or not, without using the try statement?
spence91
4.8k

votes
15

answer
652.6k

Views

What are metaclasses in Python?

What are metaclasses and what do we use them for?
e-satis
4.8k

votes
24

answer
1.5m

Views

Does Python have a ternary conditional operator?

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
4.5k

votes
26

answer
2m

Views

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

What does the if __name__ == '__main__': do? # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while True: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == '__main__': lock = thread.allocate_lock() thread.start_new_thread(...
Devoted
4.2k

votes
30

answer
3m

Views

Calling an external command in Python

How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
freshWoWer
3.8k

votes
30

answer
1.5m

Views

How to merge two 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 modifying a dict in-place. >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> pr...
Carl Meyer
3.5k

votes
25

answer
2.2m

Views

How can I safely create a nested directory in Python?

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: import os file_path = '/my/directory/filename.txt' directory = os.path.dirname(file_path) try: os.stat(directory) except: os.mkdir(dire...
Parand
3.2k

votes
15

answer
3.1m

Views

Does Python have a string 'contains' substring method?

I'm looking for a string.contains or string.indexof method in Python. I want to do: if not somestring.contains('blah'): continue
Blankman
3.1k

votes
30

answer
2m

Views

How do I sort a dictionary by value?

I have a dictionary of values read from two 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 can I sort based on the values? Note: I have read Stack Overflow question How do I sort a list of di...
Gern Blanston
3.1k

votes
22

answer
2.8m

Views

How do I list all files of a directory?

How can I list all files of a directory in Python and add them to a list?
duhhunjonn
3k

votes
30

answer
1.9m

Views

How do I check if a list is empty?

For example, if passed the following: a = [] How do I check to see if a is empty?
Ray Vega
2.9k

votes
24

answer
2.4m

Views

Difference between append vs. extend list methods in Python

What's the difference between the list methods append() and extend()?
Claudiu
2.9k

votes
22

answer
609.3k

Views

What is the difference between @staticmethod and @classmethod?

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
Daryl Spitzer
2.8k

votes
22

answer
1.5m

Views

Accessing the index in 'for' loops?

How do I access the index itself for a list like the following? 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?
Joan Venge
2.7k

votes
30

answer
1.4m

Views

Understanding slice notation

I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
Simon
2.6k

votes
18

answer
2.8m

Views

Using global variables in a function

How can I create or use a global variable in a function? If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
user46646
2.5k

votes
30

answer
1.3m

Views

Understanding Python's slice notation

I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
Simon
2.5k

votes
16

answer
451.3k

Views

How to make a chain of function decorators?

How can I make two decorators in Python that would do the following? @makebold @makeitalic def say(): return 'Hello' ...which should return: 'Hello' I'm not trying to make HTML this way in a real application - just trying to understand how decorators and decorator chaining works.
Imran
2.4k

votes
28

answer
2.9m

Views

Finding the index of an item given a list containing it in Python

For a list ['foo', 'bar', 'baz'] and an item in the list 'bar', how do I get its index (1) in Python?
Eugene M
2.4k

votes
18

answer
2.6m

Views

How can I make a time delay in Python?

I would like to know how to put a time delay in a Python script.
user46646
2.4k

votes
19

answer
2.5m

Views

Check if a given key already exists in a dictionary

I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: if 'key1' in dict.keys(): print 'blah' else: print 'boo' I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
Mohan Gulati
2.4k

votes
21

answer
543.8k

Views

Difference between __str__ and __repr__?

What is the difference between __str__ and __repr__ in Python?
Casebash
2.3k

votes
11

answer
3.3m

Views

Iterating over dictionaries using 'for' loops

I am a bit puzzled by the following code: d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] What I don't understand is the key portion. How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a v...
TopChef
2.3k

votes
30

answer
1.3m

Views

How to make a flat list out of list of lists?

I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool 'one-liner'? I tried it with reduce, but I get an error. Code l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) Error message...
Emma
2.3k

votes
30

answer
2.6m

Views

How do I install pip on Windows?

pip is a replacement for easy_install. But should I install pip using easy_install on Windows? Is there a better way?
2.3k

votes
30

answer
129.9k

Views

“Least Astonishment” and 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 return a list with only one element: [5]. The result is instead very different, and very astonishing (for a nov...
Stefano Borini
2.3k

votes
24

answer
1.1m

Views

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 __init__(self): self.variable = 'Original' self.change(self.variable) print(self.variable) def change(self, var)...
David Sykes
2.3k

votes
7

answer
606.4k

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 IDontLikeYouException: # say please except YouAreTooShortException: # stand on a ladder But if I want to do the same thing inside two differen...
inspectorG4dget
2.1k

votes
30

answer
2.4m

Views

How to get the current time in Python

What is the module/method used to get the current time?
user46646
2.1k

votes
25

answer
554.7k

Views

Is there a way to run Python on Android?

We are working on an S60 version and this platform has a nice Python API.. However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together??
e-satis
2.1k

votes
7

answer
1.4m

Views

Understanding Python super() with __init__() methods [duplicate]

This question already has an answer here: What does 'super' do in Python? 6 answers I'm trying to understand the use of super(). From the looks of it, both child classes can be created, just fine. I'm curious to know about the actual difference between the following 2 child classes. class Base(obj...
Mizipzor
2.1k

votes
13

answer
2.6m

Views

Add new keys to a dictionary?

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.
lfaraone
2k

votes
20

answer
1.3m

Views

How to clone or copy a list?

What are the options to clone or copy a list in Python? Using new_list = my_list then modifies new_list every time my_list changes. Why is this?
aF.
2k

votes
25

answer
523.3k

Views

Is there a way to run Python on Android? [closed]

We are working on an S60 version and this platform has a nice Python API.. However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together??
e-satis
1.9k

votes
18

answer
552.2k

Views

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

In the following method definitions, what does the * and ** do for param2? def foo(param1, *param2): def bar(param1, **param2):
Todd
1.9k

votes
24

answer
3.2m

Views

How do I parse a string to a float or int in Python?

In Python, how can I parse a numeric string like '545.2222' to its corresponding float value, 542.2222? Or parse the string '31' to an integer, 31? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
Tristan Havelick
1.9k

votes
30

answer
731.4k

Views

How do you split a list into evenly sized chunks?

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 list fills up, add it to the first list and empty the second list for the next round of data, but t...
jespern
1.9k

votes
30

answer
2.9m

Views

How to read a file line-by-line into a list?

How do I read every line of a file in Python and store each line as an element in a list? I want to read the file line by line and append each line to the end of the list.
Julie Raswick
1.8k

votes
28

answer
1.6m

Views

How to concatenate two lists in Python?

How do I concatenate two lists in Python? Example: listone = [1, 2, 3] listtwo = [4, 5, 6] Expected outcome: >>> joinedlist [1, 2, 3, 4, 5, 6]
y2k