Questions tagged [python]
Python is a multi-paradigm, dynamically typed, multipurpose programming language. It is designed to be quick to learn, understand, and use, and enforce a clean and uniform syntax. Please note that Python 2 is officially out of support as of 01-01-2020. Still, for version-specific Python questions, add the [python-2.7] or [python-3.x] tag. When using a Python variant (e.g., Jython, PyPy) or library (e.g., Pandas and NumPy), please include it in the tags.
1,659,853
questions
10922
votes
43answers
2.4m views
What does the “yield” keyword do?
What is the use of the yield keyword in Python, and 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....
6623
votes
35answers
3.3m views
What does if __name__ == “__main__”: do?
Given the following code, what does the if __name__ == "__main__": do?
# Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while True:
lock.acquire()
...
6492
votes
28answers
2.1m 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?
6064
votes
20answers
866k views
6007
votes
41answers
4.2m views
How do I check whether a file exists without exceptions?
How do I check if a file exists or not, without using the try statement?
5456
votes
48answers
2.2m views
How do I merge two dictionaries in a single expression in Python (taking union of dictionaries)?
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned ...
5179
votes
63answers
3.6m views
How to execute a program or call a system command from Python
How do you call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
4596
votes
27answers
2.8m views
How can I safely create a nested directory?
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/...
3980
votes
20answers
2.4m views
Accessing the index in 'for' loops?
How do I access the index in a for loop like the following?
ints = [8, 23, 45, 12, 78]
for i in ints:
print('item #{} = {}'.format(???, i))
I want to get this output:
item #1 = 8
item #2 = 23
...
3899
votes
47answers
2.6m 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 ...
3842
votes
31answers
844k views
Difference between staticmethod and classmethod
What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
3706
votes
33answers
2.0m 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....
3596
votes
10answers
4.7m 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
3513
votes
31answers
4.4m views
Finding the index of an item in a list
Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index (1) in Python?
3467
votes
21answers
5.2m 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?
3418
votes
34answers
3.4m 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 ...
3418
votes
12answers
4.6m 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 ...
3306
votes
21answers
3.3m 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 ...
3231
votes
27answers
3.4m 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?
3155
votes
43answers
3.5m views
3114
votes
20answers
3.0m views
What is the difference between Python's list methods append and extend?
What's the difference between the list methods append() and extend()?
3045
votes
5answers
963k 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:
#...
2947
votes
24answers
738k views
What is the difference between __str__ and __repr__?
What is the difference between __str__ and __repr__ in Python?
2894
votes
18answers
4.0m views
How can I 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.
2879
votes
13answers
3.2m views
How can I make a time delay in Python? [duplicate]
I would like to know how to put a time delay in a Python script.
2855
votes
17answers
546k views
How to make function decorators and chain them together?
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 ...
2841
votes
19answers
2.3m views
2832
votes
26answers
2.9m views
How do I 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]
2805
votes
28answers
1.5m 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 ...
2793
votes
22answers
1.8m views
List changes unexpectedly after assignment. How do I clone or copy it to prevent this?
While using new_list = my_list, any modifications to new_list changes my_list every time. Why is this, and how can I clone or copy the list to prevent it?
2780
votes
32answers
173k 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 ...
2749
votes
21answers
3.1m views
Convert bytes to a string
I'm using this code to get standard output from an external program:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
The ...
2716
votes
7answers
1.9m views
Understanding Python super() with __init__() methods [duplicate]
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....
2681
votes
16answers
4.2m 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 ...
2627
votes
12answers
1.4m views
2603
votes
40answers
3.1m views
How can 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?
2587
votes
22answers
829k 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):
2547
votes
25answers
3.4m views
How to iterate over rows in a DataFrame in Pandas
I have a DataFrame from Pandas:
import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print df
Output:
c1 c2
0 10 100
1 11 110
2 ...
2481
votes
63answers
1.1m 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 ...
2461
votes
8answers
1.9m views
Manually raising (throwing) an exception in Python
How can I raise an exception in Python so that it can later be caught via an except block?
2417
votes
13answers
2.3m views
2414
votes
13answers
3.4m views
Find current directory and file's directory [duplicate]
In Python, what commands can I use to find:
the current directory (where I was in the terminal when I ran the Python script), and
where the file I am executing is?
2405
votes
20answers
3.5m views
How do you change the size of figures drawn with matplotlib?
How do you change the size of figure drawn with matplotlib?
2398
votes
29answers
4.1m views
How do I parse a string to a float or int?
In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 545.2222? Or parse the string "31" to an integer, 31?
I just want to know how to parse a float str to a ...
2387
votes
11answers
3.6m views
How to select rows from a DataFrame based on column values
How can I 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 ...
2387
votes
13answers
2.0m views
How to access environment variable values?
I set an environment variable that I want to access in my Python application. How do I get its value?
2384
votes
50answers
1.5m views
2363
votes
22answers
3.3m views
Converting string into datetime
I've got a huge list of date-times like this as strings:
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them ...
2334
votes
11answers
233k views
Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?
It is my understanding that the range() function, which is actually an object type in Python 3, generates its contents on the fly, similar to a generator.
This being the case, I would have expected ...
2316
votes
13answers
3.2m views
How do I get a substring of a string in Python?
Is there a way to substring a string in Python, to get a new string from the third character to the end of the string?
Maybe like myString[2:end]?
If leaving the second part means 'till the end', ...