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
12355 votes
51 answers
3.1m 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 ...
  • 139k
7799 votes
43 answers
4.3m views

What does if __name__ == "__main__": do in Python?

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 ...
  • 172k
7535 votes
30 answers
2.6m views

Does Python have a ternary conditional operator?

Is there a ternary conditional operator in Python?
  • 172k
7013 votes
24 answers
1.1m views

What are metaclasses in Python?

What are metaclasses? What are they used for?
  • 564k
6822 votes
40 answers
5.0m 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?
  • 74.9k
6515 votes
43 answers
2.9m views

How do I merge two dictionaries in a single expression?

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 ...
  • 118k
5837 votes
64 answers
4.2m views

How do I execute a program or call a system command?

How do I call an external command within Python as if I'd typed it in a shell or command prompt?
  • 60.1k
5365 votes
28 answers
3.4m views

How can I safely create a nested directory?

How do I check if the directory into which a file is going to be written does exist, and if it does not, create the directory using Python?
  • 100k
4912 votes
26 answers
3.5m 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 = ...
  • 302k
4901 votes
33 answers
3.7m 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 ...
  • 49.8k
4431 votes
34 answers
1.0m views

Difference between @staticmethod and @classmethod

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
4375 votes
36 answers
2.7m views

Understanding slicing

I need a good explanation (references are a plus) on Python slicing.
  • 76.8k
4178 votes
42 answers
5.7m 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.1k
4036 votes
16 answers
5.4m 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 ...
  • 42k
3771 votes
24 answers
3.8m 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 ...
  • 148k
3670 votes
31 answers
5.9m 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) ...
  • 118k
3631 votes
52 answers
4.0m views

How do I get the current time?

How do I get the current time?
  • 148k
3610 votes
6 answers
1.3m 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: #...
3588 votes
10 answers
6.2m 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
  • 253k
3501 votes
28 answers
898k views

What is the difference between __str__ and __repr__?

What is the difference between __str__ and __repr__ in Python?
  • 111k
3489 votes
24 answers
4.4m 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] >>...
3467 votes
21 answers
7.3m 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.2k
3448 votes
23 answers
3.1m views

How to copy files?

How do I copy a file in Python?
  • 80.6k
3416 votes
34 answers
4.8m 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 ...
3387 votes
14 answers
2.0m views

What is __init__.py for?

What is __init__.py for in a Python source directory?
  • 78.2k
3386 votes
19 answers
5.0m 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.
  • 48.6k
3245 votes
31 answers
3.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]
  • 64.7k
3232 votes
32 answers
233k 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 ...
3230 votes
27 answers
4.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?
  • 183k
3190 votes
16 answers
5.3m 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
  • 34.8k
3161 votes
39 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....
3155 votes
25 answers
1.2m views

What does ** (double star/asterisk) and * (star/asterisk) do for parameters in Python?

What do *args and **kwargs mean? def foo(x, y, *args): def bar(x, y, **kwargs):
  • 32.9k
3154 votes
23 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?
  • 63.5k
3122 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?
  • 148k
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()?
  • 219k
3084 votes
15 answers
2.9m views

How do I delete a file or folder in Python?

How do I delete a file or folder?
  • 31.2k
3081 votes
7 answers
2.4m 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(...
  • 49.8k
3068 votes
18 answers
621k 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>&...
  • 84.1k
3029 votes
26 answers
5.3m views

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

How do I change the size of figure drawn with Matplotlib?
  • 36.1k
2996 votes
11 answers
2.7m 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?
  • 247k
2942 votes
71 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.2k
2937 votes
62 answers
2.1m views

How do I print colored text to the terminal?

How do I output colored text to the terminal in Python?
  • 29.6k
2921 votes
15 answers
2.6m views

How do I access environment variables in Python?

How do I get the value of an environment variable in Python?
  • 30.3k
2862 votes
26 answers
4.4m 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"
  • 232k
2828 votes
13 answers
4.3m views

Find the current directory and file's directory [duplicate]

How do I determine: the current directory (where I was in the terminal when I ran the Python script), and where the Python file I am executing is?
  • 58.3k
2822 votes
12 answers
324k 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 ...
  • 40.6k
2717 votes
35 answers
5.3m 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']
  • 27.3k
2679 votes
16 answers
5.6m 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 ...
  • 28.2k
2677 votes
11 answers
2.5m views

How can I remove a key from a Python dictionary?

Is there a one-line way of deleting a key from a dictionary without raising a KeyError? if 'key' in my_dict: del my_dict['key']
  • 35.4k
2657 votes
31 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 ...

1
2 3 4 5
41148