Questions tagged [python]

Python is a multi-paradigm, 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
12546 votes
51 answers
3.2m views

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 ...
  • 142k
7958 votes
45 answers
4.4m 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 ...
  • 175k
7669 votes
31 answers
2.7m views

Does Python have a ternary conditional operator?

Is there a ternary conditional operator in Python?
  • 175k
7161 votes
25 answers
1.1m views

What are metaclasses in Python?

What are metaclasses? What are they used for?
  • 572k
6928 votes
40 answers
5.2m 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?
  • 76.1k
6656 votes
43 answers
3.0m 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 ...
  • 120k
5932 votes
65 answers
4.3m 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?
  • 61.1k
5468 votes
28 answers
3.5m views

How can I safely create a directory (possibly including intermediate directories)?

I am writing a file using Python, and I want it to be placed in a specific path. How can I safely make sure that the path exists? That is: how can I check whether the folder exists, along with its ...
  • 102k
5093 votes
26 answers
3.8m views

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 = ...
  • 310k
5083 votes
36 answers
3.9m 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 comprehension, the problem can ...
  • 51.6k
4509 votes
35 answers
1.0m views

Difference between @staticmethod and @classmethod

What is the difference between a method decorated with @staticmethod and one decorated with @classmethod?
4458 votes
38 answers
2.8m views

Understanding slicing

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....
  • 77.9k
4259 votes
43 answers
5.9m 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?
  • 46.9k
4123 votes
16 answers
5.5m 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 ...
  • 42.9k
3842 votes
25 answers
3.9m views

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 ...
  • 151k
3815 votes
32 answers
6.4m views

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 be able to access its elements (values in cells) ...
  • 122k
3717 votes
54 answers
4.1m views

How do I get the current time?

How do I get the current time?
  • 151k
3688 votes
6 answers
1.4m 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: # ...
3599 votes
22 answers
4.7m views

Convert bytes to a string

I captured the standard output of an external program into a bytes object: >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>...
3598 votes
19 answers
3.3m views

How to copy files

How do I copy a file in Python?
  • 82.9k
3588 votes
10 answers
6.3m 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
  • 257k
3588 votes
28 answers
932k views

What is the difference between __str__ and __repr__?

What is the difference between __str__ and __repr__ in Python?
  • 113k
3512 votes
14 answers
2.1m views

What is __init__.py for?

What is __init__.py for in a Python source directory?
  • 80.4k
3467 votes
21 answers
7.6m 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?
  • 44.6k
3441 votes
20 answers
5.1m views

How can I add new keys to a dictionary?

How do I add a key to an existing dictionary? It doesn't have an .add() method.
  • 49.2k
3416 votes
34 answers
5.0m 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 ...
3302 votes
16 answers
5.7m 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
  • 35.9k
3298 votes
34 answers
245k 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 ...
3254 votes
26 answers
1.2m 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 ...
  • 33.9k
3244 votes
31 answers
4.1m 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]
  • 65.1k
3229 votes
27 answers
4.5m 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?
  • 185k
3220 votes
41 answers
1.9m views

How do I pass a variable by reference?

Are parameters passed by reference or by value? How do I pass by reference so that the code below outputs 'Changed' instead of 'Original'? class PassByReference: def __init__(self): self....
  • 47.8k
3202 votes
24 answers
2.1m 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?
  • 64.3k
3188 votes
15 answers
3.1m views

How can I delete a file or folder in Python?

How can I delete a file or folder?
  • 32.2k
3149 votes
13 answers
3.6m views

How do I make a time delay? [duplicate]

How do I put a time delay in a Python script?
  • 151k
3141 votes
7 answers
2.5m 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(...
  • 50.5k
3113 votes
20 answers
3.2m views

What is the difference between Python's list methods append and extend?

What's the difference between the list methods append() and extend()?
  • 222k
3113 votes
14 answers
5.7m views

How do I change the size of figures drawn with Matplotlib?

How do I change the size of figure drawn with Matplotlib?
  • 37k
3104 votes
20 answers
633k 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>&...
  • 85.7k
3070 votes
11 answers
2.8m 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?
  • 254k
3034 votes
16 answers
2.7m views

How can I access environment variables in Python?

How can I get the value of an environment variable in Python?
  • 31.7k
3032 votes
64 answers
2.2m views

How do I print colored text to the terminal?

How do I output colored text to the terminal in Python?
  • 30.5k
3009 votes
67 answers
1.5m 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 How to iterate over a list in chunks if the data result will be used directly for a loop, and does not need to be stored. For ...
  • 31.9k
2906 votes
12 answers
345k 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 ...
  • 42k
2903 votes
26 answers
4.5m views

Convert string "Jun 1 2005 1:33PM" into datetime

How do I convert the following string to a datetime object? "Jun 1 2005 1:33PM"
  • 234k
2881 votes
13 answers
4.4m 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?
  • 59.7k
2813 votes
35 answers
5.7m 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']
  • 28.2k
2763 votes
11 answers
2.6m 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 ...
  • 36k
2686 votes
32 answers
4.6m views

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

How can I convert a str to float? "545.2222" → 545.2222 How can I convert a str to int? "31" → 31 For the reverse, see Convert integer to string in Python and ...
2686 votes
20 answers
1.2m views

How do I sort a list of dictionaries by a value of the dictionary?

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
42462