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
12733 votes
50 answers

What does the "yield" keyword do in Python?

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 ...
Alex. S.'s user avatar
  • 144k
8091 votes
46 answers

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
  • 178k
7798 votes
32 answers

Does Python have a ternary conditional operator?

Is there a ternary conditional operator in Python?
Devoted's user avatar
  • 178k
7281 votes
25 answers

What are metaclasses in Python?

What are metaclasses? What are they used for?
Bite code's user avatar
  • 580k
7029 votes
40 answers

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
  • 77.3k
6809 votes
43 answers

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
  • 122k
6035 votes
66 answers

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
  • 62.1k
5568 votes
27 answers

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
  • 103k
5274 votes
27 answers

Accessing the index in 'for' loops

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
  • 317k
5211 votes
33 answers

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
  • 52.9k
4584 votes
36 answers

@staticmethod vs @classmethod in Python

What is the difference between a method decorated with @staticmethod and one decorated with @classmethod?
Daryl Spitzer's user avatar
4526 votes
38 answers

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? Please include references where appropriate....
Simon's user avatar
  • 78.8k
4326 votes
45 answers

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?
Eugene M's user avatar
  • 47.6k
4218 votes
17 answers

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
  • 43.9k
3966 votes
33 answers

How to iterate over rows in a DataFrame in Pandas

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
  • 125k
3908 votes
25 answers

Using global variables 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
  • 154k
3794 votes
54 answers

How do I get the current time?

How do I get the current time?
user46646's user avatar
  • 154k
3768 votes
6 answers

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: # ...
inspectorG4dget's user avatar
3715 votes
21 answers

How to copy files

How do I copy a file in Python?
Matt's user avatar
  • 84.6k
3691 votes
24 answers

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
3643 votes
28 answers

What is the difference between __str__ and __repr__?

What is the difference between __str__ and __repr__ in Python?
Casebash's user avatar
  • 115k
3632 votes
14 answers

What is for?

What is for in a Python source directory?
Mat's user avatar
  • 82.5k
3587 votes
10 answers

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
  • 260k
3484 votes
21 answers

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
  • 49.6k
3466 votes
21 answers

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
  • 44.9k
3414 votes
34 answers

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
3412 votes
17 answers

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
  • 37.1k
3363 votes
34 answers

"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
3324 votes
28 answers

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
  • 34.6k
3289 votes
17 answers

How can I delete a file or folder in Python?

How can I delete a file or folder in Python?
Zygimantas's user avatar
  • 33.2k
3264 votes
40 answers

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
  • 48.5k
3241 votes
24 answers

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
  • 65.1k
3239 votes
31 answers

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.4k
3228 votes
27 answers

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
  • 187k
3188 votes
13 answers

How do I make a time delay? [duplicate]

How do I put a time delay in a Python script?
user46646's user avatar
  • 154k
3188 votes
7 answers

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.2k
3166 votes
11 answers

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
  • 261k
3165 votes
14 answers

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
  • 37.6k
3157 votes
16 answers

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
  • 32.8k
3133 votes
21 answers

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
  • 87.4k
3120 votes
65 answers

How do I print colored text to the terminal?

How do I output colored text to the terminal in Python?
aboSamoor's user avatar
  • 31.4k
3111 votes
20 answers

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
  • 224k
3076 votes
69 answers

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
  • 32.5k
2973 votes
12 answers

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
  • 43.1k
2940 votes
13 answers

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
  • 61.2k
2935 votes
27 answers

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
  • 236k
2904 votes
36 answers

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.1k
2830 votes
11 answers

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
  • 36.7k
2744 votes
22 answers

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}, ...
2736 votes
40 answers

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 3 4 5