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. Please note that Python 2 is officially out of support as of 2020-01-01. 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, NumPy), please include it in the tags.

Filter by
Sorted by
Tagged with
12893 votes
50 answers
3.3m 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 ...
Alex. S.'s user avatar
  • 145k
8216 votes
46 answers
4.6m 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 ...
Devoted's user avatar
  • 181k
7919 votes
32 answers
2.9m views

Does Python have a ternary conditional operator?

Is there a ternary conditional operator in Python?
Devoted's user avatar
  • 181k
7375 votes
25 answers
1.2m views

What are metaclasses in Python?

What are metaclasses? What are they used for?
Bite code's user avatar
  • 588k
7135 votes
41 answers
5.5m 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?
spence91's user avatar
  • 78.5k
6942 votes
43 answers
3.3m 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 ...
Carl Meyer's user avatar
  • 124k
6124 votes
66 answers
4.7m 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?
freshWoWer's user avatar
  • 63.1k
5663 votes
27 answers
3.7m 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.
Parand's user avatar
  • 105k
5447 votes
28 answers
4.5m 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 = ...
Joan Venge's user avatar
  • 324k
5328 votes
34 answers
4.3m 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 ...
Emma's user avatar
  • 54.1k
4651 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?
Daryl Spitzer's user avatar
4590 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 ...
Simon's user avatar
  • 79.8k
4392 votes
46 answers
6.3m 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?
Eugene M's user avatar
  • 48.3k
4310 votes
17 answers
5.8m 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 ...
TopChef's user avatar
  • 44.8k
4088 votes
34 answers
7.3m 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 ...
Roman's user avatar
  • 128k
3957 votes
26 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 ...
user46646's user avatar
  • 156k
3860 votes
54 answers
4.4m views

How do I get the current time in Python?

How do I get the current time in Python?
user46646's user avatar
  • 156k
3831 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: # ...
inspectorG4dget's user avatar
3810 votes
21 answers
3.7m views

How to copy files

How do I copy a file in Python?
Matt's user avatar
  • 86.4k
3763 votes
23 answers
5.0m 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] >>> ...
Tomas Sedovic's user avatar
3744 votes
14 answers
2.5m views

What is __init__.py for?

What is __init__.py for in a Python source directory?
Mat's user avatar
  • 84.4k
3699 votes
28 answers
988k views

What is the difference between __str__ and __repr__?

What is the difference between __str__ and __repr__ in Python?
Casebash's user avatar
  • 117k
3587 votes
10 answers
6.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
Blankman's user avatar
  • 264k
3529 votes
21 answers
5.3m 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.
lfaraone's user avatar
  • 50.1k
3515 votes
17 answers
6.4m 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
szli's user avatar
  • 38.1k
3466 votes
21 answers
8.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?
duhhunjonn's user avatar
  • 45.2k
3420 votes
34 answers
268k 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 called with ...
Stefano Borini's user avatar
3413 votes
34 answers
5.3m 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 ...
Gern Blanston's user avatar
3391 votes
18 answers
3.6m views

How can I delete a file or folder in Python?

How can I delete a file or folder in Python?
Zygimantas's user avatar
  • 34.2k
3383 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 ...
Todd's user avatar
  • 35.2k
3302 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?
aF.'s user avatar
  • 66k
3298 votes
41 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, ...
David Sykes's user avatar
  • 49.1k
3264 votes
17 answers
3.0m views

How can I access environment variables in Python?

How can I get the value of an environment variable in Python?
Amit Yadav's user avatar
  • 33.6k
3238 votes
31 answers
4.4m 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]
y2k's user avatar
  • 65.7k
3233 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?
TIMEX's user avatar
  • 266k
3226 votes
27 answers
4.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's user avatar
  • 190k
3222 votes
7 answers
2.7m 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(...
Mizipzor's user avatar
  • 51.7k
3220 votes
13 answers
3.7m views

How do I make a time delay? [duplicate]

How do I put a time delay in a Python script?
user46646's user avatar
  • 156k
3207 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?
tatwright's user avatar
  • 38.1k
3196 votes
65 answers
2.5m views

How do I print colored text to the terminal?

How do I output colored text to the terminal in Python?
aboSamoor's user avatar
  • 32.2k
3160 votes
22 answers
659k 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>&...
Imran's user avatar
  • 89.2k
3118 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?.
jespern's user avatar
  • 33k
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()?
Claudiu's user avatar
  • 227k
3013 votes
12 answers
365k 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 ...
Rick's user avatar
  • 44.1k
3000 votes
13 answers
4.8m 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?
John Howard's user avatar
  • 62.5k
2967 votes
33 answers
6.4m 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']
user1504276's user avatar
  • 29.8k
2959 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?
Oli's user avatar
  • 238k
2899 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 ...
Tony's user avatar
  • 37.5k
2789 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.
thedjpetersen's user avatar
2785 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}, ...

1
2 3 4 5
43899