Questions tagged [python]
Python is a dynamically typed, multi-purpose programming language. It is designed to be quick to learn, understand, and use, and enforces a clean and uniform syntax. Note that Python 2 reached end-of-life on January 1st, 2020. For version-specific Python questions, add the version tag (e.g. [python-3.x] or [python-3.9]). When using a Python variant (e.g. Jython, PyPy) or library (e.g. Pandas, NumPy), please include it in the tags.
python
2,203,211
questions
12947
votes
52
answers
3.4m
views
What does the "yield" keyword do in Python?
What functionality does the yield keyword in Python provide?
For example, I'm trying to understand this code1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and ...
8257
votes
47
answers
4.7m
views
What does if __name__ == "__main__": do?
What does this do, and why should one include the if statement?
if __name__ == "__main__":
print("Hello, World!")
If you are trying to close a question where someone should be ...
7952
votes
31
answers
2.9m
views
Does Python have a ternary conditional operator?
Is there a ternary conditional operator in Python?
7402
votes
26
answers
1.2m
views
What are metaclasses in Python?
What are metaclasses? What are they used for?
7184
votes
41
answers
5.6m
views
How do I check whether a file exists without exceptions?
How do I check whether a file exists or not, without using the try statement?
6983
votes
43
answers
3.4m
views
How do I merge two dictionaries in a single expression in Python?
I want to merge two dictionaries into a new dictionary.
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
Whenever a key k is present in both ...
6168
votes
66
answers
4.8m
views
How do I execute a program or call a system command?
How do I call an external command within Python as if I had typed it in a shell or command prompt?
5698
votes
27
answers
3.8m
views
How do I create a directory, and any missing parent directories?
How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command mkdir -p /path/to/nested/directory does this.
5497
votes
28
answers
4.6m
views
How to access the index value in a 'for' loop?
How do I access the index while iterating over a sequence with a for loop?
xs = [8, 23, 45]
for x in xs:
print("item #{} = {}".format(index, x))
Desired output:
item #1 = 8
item #2 = ...
5371
votes
34
answers
4.4m
views
How do I make a flat list out of a list of lists?
I have a list of lists like
[
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
How can I flatten it to get [1, 2, 3, 4, 5, 6, 7, 8, 9]?
If your list of lists comes from a nested list ...
4681
votes
36
answers
1.1m
views
What is the difference between @staticmethod and @classmethod in Python?
What is the difference between a method decorated with @staticmethod and one decorated with @classmethod?
4609
votes
38
answers
3.1m
views
How slicing in Python works
How does Python's slice notation work? That is: when I write code like a[x:y:z], a[:], a[::2] etc., how can I understand which elements end up in the slice?
See Why are slice and range upper-bound ...
4415
votes
46
answers
6.4m
views
How to find the index for a given item in a list?
Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index 1?
4329
votes
17
answers
5.9m
views
Iterating over dictionaries using 'for' loops
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
How does Python recognize that it needs only to read the key from the dictionary? Is key a special keyword, or is ...
4119
votes
34
answers
7.5m
views
How can I iterate over rows in a Pandas DataFrame?
I have a pandas dataframe, df:
c1 c2
0 10 100
1 11 110
2 12 120
How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name ...
3982
votes
27
answers
4.1m
views
How to use a global variable in a function?
How do I create or use a global variable inside a function?
How do I use a global variable that was defined in one function inside other functions?
Failing to use the global keyword where appropriate ...
3897
votes
54
answers
4.4m
views
How do I get the current time in Python?
How do I get the current time in Python?
3858
votes
6
answers
1.5m
views
How to catch multiple exceptions in one line? (in the "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:
# ...
3832
votes
21
answers
3.8m
views
How to copy files
How do I copy a file in Python?
3792
votes
14
answers
2.5m
views
What is __init__.py for?
What is __init__.py for in a Python source directory?
3785
votes
23
answers
5.1m
views
Convert bytes to a string in Python 3
I captured the standard output of an external program into a bytes object:
>>> from subprocess import *
>>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>> ...
3724
votes
28
answers
1.0m
views
What is the difference between __str__ and __repr__?
What is the difference between __str__ and __repr__ in Python?
3586
votes
10
answers
6.9m
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
3550
votes
20
answers
5.4m
views
How can I add new keys to a dictionary?
How do I add a new key to an existing dictionary? It doesn't have an .add() method.
3541
votes
18
answers
6.5m
views
How do I 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 column_name = some_value
3465
votes
21
answers
8.4m
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?
3438
votes
34
answers
272k
views
The Mutable Default Argument in Python
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 called with ...
3424
votes
18
answers
3.7m
views
How can I delete a file or folder in Python?
How can I delete a file or folder in Python?
3413
votes
34
answers
5.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 ...
3402
votes
28
answers
1.4m
views
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
What do *args and **kwargs mean in these function definitions?
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
See What do ** (double star/asterisk) and * (star/asterisk) mean in a ...
3316
votes
17
answers
3.1m
views
How can I access environment variables in Python?
How can I get the value of an environment variable in Python?
3314
votes
24
answers
2.2m
views
How do I clone a list so that it doesn't change unexpectedly after assignment?
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? For example:
>>> my_list = [1, 2, 3]
...
3313
votes
42
answers
2.1m
views
How do I pass a variable by reference?
I wrote this class for testing:
class PassByReference:
def __init__(self):
self.variable = 'Original'
self.change(self.variable)
print(self.variable)
def change(self, ...
3250
votes
11
answers
3.1m
views
Manually raising (throwing) an exception in Python
How do I raise an exception in Python so that it can later be caught via an except block?
3238
votes
31
answers
4.5m
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]
3236
votes
13
answers
3.8m
views
How do I make a time delay? [duplicate]
How do I put a time delay in a Python script?
3234
votes
7
answers
2.8m
views
Understanding Python super() with __init__() methods [duplicate]
Why is super() used?
Is there a difference between using Base.__init__ and super().__init__?
class Base(object):
def __init__(self):
print "Base created"
class ChildA(...
3224
votes
16
answers
6.1m
views
How do I change the size of figures drawn with Matplotlib?
How do I change the size of figure drawn with Matplotlib?
3222
votes
27
answers
5.0m
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?
3217
votes
66
answers
2.5m
views
How do I print colored text to the terminal?
How do I output colored text to the terminal in Python?
3168
votes
22
answers
664k
views
How do I make function decorators and chain them together?
How do I make two decorators in Python that would do the following?
@make_bold
@make_italic
def say():
return "Hello"
Calling say() should return:
"<b><i>Hello</i>&...
3127
votes
70
answers
1.7m
views
How do I split a list into equally-sized chunks?
How do I split a list of arbitrary length into equal sized chunks?
See also: How to iterate over a list in chunks.
To chunk strings, see Split string every nth character?.
3111
votes
20
answers
3.3m
views
What is the difference between Python's list methods append and extend?
What's the difference between the list methods append() and extend()?
3026
votes
13
answers
5.0m
views
Find the current directory and file's directory [duplicate]
How do I determine:
the current directory (where I was in the shell when I ran the Python script), and
where the Python file I am executing is?
3026
votes
12
answers
368k
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 ...
2993
votes
33
answers
6.6m
views
Renaming column names in Pandas
I want to change the column labels of a Pandas DataFrame from
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
2969
votes
26
answers
4.6m
views
Convert string "Jun 1 2005 1:33PM" into datetime
I have a huge list of datetime strings like the following
["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"]
How do I convert them into datetime objects?
2928
votes
11
answers
2.8m
views
How can I remove a key from a Python dictionary?
I want to remove a key from a dictionary if it is present. I currently use this code:
if key in my_dict:
del my_dict[key]
Without the if statement, the code will raise KeyError if the key is not ...
2803
votes
22
answers
1.4m
views
How to sort a list of dictionaries by a value of the dictionary in Python?
How do I sort a list of dictionaries by a specific key's value? Given:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
When sorted by name, it should become:
[{'name': 'Bart', 'age': 10}, ...
2802
votes
62
answers
1.9m
views
How to upgrade all Python packages with pip
Is it possible to upgrade all Python packages at one time with pip?
Note: that there is a feature request for this on the official issue tracker.