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
202,165
questions
245
votes
5
answers
55k
views
How to make good reproducible pandas examples
Having spent a decent amount of time watching both the r and pandas tags on SO, the impression that I get is that pandas questions are less likely to contain reproducible data. This is something that ...
556
votes
18
answers
269k
views
How do I create variable variables?
I know that some other languages, such as PHP, support a concept of "variable variable names" - that is, the contents of a string can be used as part of a variable name.
I heard that this is ...
760
votes
22
answers
1.1m
views
Asking the user for input until they give a valid response
I am writing a program that accepts user input.
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
...
849
votes
31
answers
568k
views
How to test multiple variables for equality against a single value?
I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:
x = 0
y ...
956
votes
19
answers
80k
views
List of lists changes reflected across sublists unexpectedly
I created a list of lists:
>>> xs = [[1] * 4] * 3
>>> print(xs)
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
Then, I changed one of the innermost values:
>>> xs[0][0] = 5
>...
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 ...
628
votes
5
answers
75k
views
How can I pivot a dataframe? [closed]
What is pivot?
How do I pivot?
Long format to wide format?
I've seen a lot of questions that ask about pivot tables, even if they don't know it. It is virtually impossible to write a canonical ...
931
votes
8
answers
436k
views
Pandas Merging 101
How can I perform a (INNER| (LEFT|RIGHT|FULL) OUTER) JOIN with pandas?
How do I add NaNs for missing rows after a merge?
How do I get rid of NaNs after merging?
Can I merge on the index?
How do I ...
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 ...
55
votes
6
answers
91k
views
I'm getting an IndentationError (or a TabError). How do I fix it?
I have a Python script:
if True:
if False:
print('foo')
print('bar')
However, when I attempt to run my script, Python raises an IndentationError:
File "script.py", line 4
...
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]
...
259
votes
10
answers
1.1m
views
How can I read inputs as numbers?
Why are x and y strings instead of ints in the below code?
(Note: in Python 2.x use raw_input(). In Python 3.x use input(). raw_input() was renamed to input() in Python 3.x)
play = True
while play:
...
931
votes
25
answers
933k
views
How to remove items from a list while iterating?
I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
for tup in somelist:
if determine(tup):
code_to_remove_tup
What should I ...
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 ...
136
votes
8
answers
242k
views
Selenium - wait until element is present, visible and interactable
I have a Selenium script (Python) that clicks a reply button to make the class anonemail appear. The time it takes for the class anonemail to appear varies. Because of that I have to use sleep until ...
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?.
181
votes
8
answers
48k
views
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
I am writing a security system that denies access to unauthorized users.
name = input("Hello. Please enter your name: ")
if name == "Kevin" or "Jon" or "Inbar":
...
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, ...
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 ...
1435
votes
26
answers
2.4m
views
How to deal with SettingWithCopyWarning in Pandas
Background
I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this:
E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value ...
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 ...
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 ...
530
votes
9
answers
268k
views
Short description of the scoping rules
What exactly are the Python scoping rules?
If I have some code:
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
Where is x found? Some possible ...
108
votes
5
answers
43k
views
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
My code is:
from Tkinter import *
admin = Tk()
def button(an):
print(an)
print('het')
b = Button(admin, text='as', command=button('hey'))
b.pack()
mainloop()
The button doesn't work, it ...
2
votes
2
answers
5k
views
Of the many findElement(s)/By functions in Selenium, when would you use one over the other?
Selenium includes findElement functions, like so...
.find_element_by_
id
link_text
partial_link_text
name
class_name
tag_name
css_selector
xpath
It's apparent that some are limited by design due ...
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
115
votes
4
answers
135k
views
Why does my recursive function return None?
I have this function that calls itself:
def get_input():
my_var = input('Enter "a" or "b": ')
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
...
88
votes
4
answers
145k
views
Why do I get "AttributeError: NoneType object has no attribute" using Tkinter? Where did the None value come from?
I've created this simple GUI:
from tkinter import *
root = Tk()
def grabText(event):
print(entryBox.get())
entryBox = Entry(root, width=60).grid(row=2, column=1, sticky=W)
grabBtn = Button(...
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?
307
votes
14
answers
112k
views
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
When I try this code:
a, b, c = (1, 2, 3)
def test():
print(a)
print(b)
print(c)
c += 1
test()
I get an error from the print(c) line that says:
UnboundLocalError: local variable 'c' ...
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 ...
1276
votes
9
answers
1.3m
views
How do I iterate through two lists in parallel?
I have two iterables, and I want to go over them in pairs:
foo = [1, 2, 3]
bar = [4, 5, 6]
for (f, b) in iterate_together(foo, bar):
print("f:", f, " | b:", b)
That should ...
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 ...
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 ...
91
votes
5
answers
98k
views
Why does Tkinter image not show up if created in a function?
This code works:
import tkinter
root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.grid(row = 0, column = 0)
photo = tkinter.PhotoImage(file = './test.gif')
canvas.create_image(0, 0, image=...
99
votes
5
answers
53k
views
Importing a library from (or near) a script with the same name raises "AttributeError: module has no attribute" or an ImportError or NameError
I have a script named requests.py that needs to use the third-party requests package. The script either can't import the package, or can't access its functionality.
Why isn't this working, and how do ...
192
votes
9
answers
82k
views
Why is using 'eval' a bad practice?
I use the following class to easily store data of my songs.
class Song:
"""The class to store the details of each song"""
attsToStore=('Name', 'Artist', 'Album', '...
562
votes
54
answers
212k
views
Flatten an irregular (arbitrarily nested) list of lists
Yes, I know this subject has been covered before:
Python idiom to chain (flatten) an infinite iterable of finite iterables?
Flattening a shallow list in Python
Comprehension for flattening a sequence ...
42
votes
4
answers
10k
views
Why do these list methods (append, sort, extend, remove, clear, reverse) return None rather than the resulting list?
I've noticed that many operations on lists that modify the list's contents will return None, rather than returning the list itself. Examples:
>>> mylist = ['a', 'b', 'c']
>>> empty = ...
905
votes
21
answers
749k
views
How to convert string representation of list to a list
I was wondering what the simplest way is to convert a string representation of a list like the following to a list:
x = '[ "A","B","C" , " D"]'
Even in cases ...
499
votes
14
answers
846k
views
How do I create a new column where the values are selected based on an existing column?
How do I add a color column to the following dataframe so that color='green' if Set == 'Z', and color='red' otherwise?
Type Set
1 A Z
2 B Z
3 B X
4 C Y
18
votes
1
answer
20k
views
WebDriverWait not working as expected
I am working with selenium to scrape some data.
There is button on the page that I am clicking say "custom_cols". This button opens up a window for me where I can select my columns.
This new window ...
1794
votes
15
answers
658k
views
Relative imports for the billionth time
I've been here:
PEP 328 – Imports: Multi-Line and Absolute/Relative
Modules, Packages
Python packages: relative imports
Python relative import example code does not work
Relative imports in Python 2....
874
votes
12
answers
1.3m
views
How to filter Pandas dataframe using 'in' and 'not in' like in SQL
How can I achieve the equivalents of SQL's IN and NOT IN?
I have a list with the required values. Here's the scenario:
df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
...
107
votes
12
answers
25k
views
Strange result when removing item from a list while iterating over it in Python
I've got this piece of code:
numbers = list(range(1, 50))
for i in numbers:
if i < 20:
numbers.remove(i)
print(numbers)
But, the result I'm getting is:
[2, 4, 6, 8, 10, 12, 14, 16, ...
536
votes
20
answers
393k
views
How to get the Cartesian product of multiple lists
How can I get the Cartesian product (every possible combination of values) from a group of lists?
For example, given
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
How do I get this?
[(1, 'a',...
1335
votes
26
answers
1.1m
views
What is the purpose of the `self` parameter? Why is it needed?
Consider this example:
class MyClass:
def func(self, name):
self.name = name
I know that self refers to the specific instance of MyClass. But why must func explicitly include self as a ...
7952
votes
31
answers
2.9m
views
Does Python have a ternary conditional operator?
Is there a ternary conditional operator in Python?
866
votes
15
answers
2.5m
views
Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
I want to filter my dataframe with an or condition to keep rows with a particular column's values that are outside the range [-0.25, 0.25]. I tried:
df = df[(df['col'] < -0.25) or (df['col'] > 0....
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 ...