Questions tagged [python]

Python is a multi-paradigm, dynamically typed, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax. Two similar but incompatible versions of Python are commonly in use, Python 2.7 and 3.x. For version-specific Python questions, use the [python-2.7] or [python-3.x] tags. When using a Python variant or library (i.e Jython, Pypy, Pandas, Numpy), please include it in the tags.

532
votes
21answers
154k views

How to test multiple variables against a 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 ...
2707
votes
31answers
1.4m views

Understanding slice notation

I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it....
2296
votes
32answers
131k 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 to always ...
478
votes
18answers
337k views

Asking the user for input until they give a valid response

I am writing a program that must accept input from the user. #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 >= ...
2063
votes
20answers
1.3m views

How to clone or copy a list?

What are the options to clone or copy a list in Python? While using new_list = my_list, any modifications to new_list changes my_list everytime. Why is this?
503
votes
12answers
23k views

List of lists changes reflected across sublists unexpectedly

I needed to create a list of lists in Python, so I typed the following: myList = [[1] * 4] * 3 The list looked like this: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] Then I changed one of the ...
275
votes
16answers
105k views

How do I create a variable number of variables?

How do I accomplish variable variables in Python? Here is an elaborative manual entry, for instance: Variable variables I have heard this is a bad idea in general though, and it is a security hole ...
222
votes
5answers
13k views

How to make good reproducible pandas examples [closed]

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 ...
824
votes
24answers
393k 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 ...
2545
votes
39answers
1.5m views

How to make a flat list out of list of lists

I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with reduce, but I get an ...
1873
votes
59answers
736k views

How do you split a list into evenly sized chunks?

I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second ...
2295
votes
24answers
1.1m views

How do I pass a variable by reference?

The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' class PassByReference: def ...
259
votes
19answers
675k 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: ...
234
votes
1answer
11k views

How to pivot a dataframe

What is pivot? How do I pivot? Is this a pivot? Long format to wide format? I've seen a lot of questions that ask about pivot tables. Even if they don't know that they are asking about pivot tables, ...
1910
votes
18answers
558k views

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

In the following method definitions, what does the * and ** do for param2? def foo(param1, *param2): def bar(param1, **param2):
431
votes
7answers
228k 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 ...
2768
votes
18answers
2.9m views

Using global variables in a function

How can I create or use a global variable in a function? If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable ...
4190
votes
56answers
3.0m views

Calling an external command in Python

How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
9169
votes
42answers
2.0m views

What does the “yield” keyword do?

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....
4927
votes
28answers
2.2m views

What does if __name__ == “__main__”: do?

What does the if __name__ == "__main__": do? # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while True: lock.acquire() time.sleep(...
164
votes
2answers
12k views

Pandas Merging 101

How to perform a (LEFT|RIGHT|FULL) (INNER|OUTER) join with pandas? How do I add NaNs for missing rows after merge? How do I get rid of NaNs after merging? Can I merge on the index? Cross join with ...
386
votes
42answers
108k views

Flatten an irregular list of lists

Yes, I know this subject has been covered before (here, here, here, here), but as far as I know, all solutions, except for one, fail on a list like this: L = [[[1, 2, 3], [4, 5]], 6] Where the ...
3394
votes
42answers
2.2m 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 ...
55
votes
7answers
17k views

Why is Button parameter “command” executed when declared?

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 ...
437
votes
11answers
53k views

“is” operator behaves unexpectedly with integers

Why does the following behave unexpectedly in Python? >>> a = 256 >>> b = 256 >>> a is b True # This is an expected result >>> a = 257 >>> b = ...
5135
votes
28answers
1.7m views

Does Python have a ternary conditional operator?

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
5093
votes
15answers
692k views

What are metaclasses in Python?

What are metaclasses and what do we use them for?
979
votes
19answers
750k views

What is the purpose of self?

What is the purpose of the self word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a ...
112
votes
8answers
30k views

Why is using 'eval' a bad practice?

I am using 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', 'Genre', 'Location') ...
2388
votes
34answers
2.7m views

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?
427
votes
11answers
447k 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 ...
123
votes
8answers
21k views

How to avoid having class data shared among instances?

What I want is this behavior: class a: list = [] x = a() y = a() x.list.append(1) y.list.append(2) x.list.append(3) y.list.append(4) print(x.list) # prints [1, 3] print(y.list) # prints [2, 4] ...
654
votes
24answers
632k views

Is there any way to kill a Thread?

Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
37
votes
2answers
9k views

Importing installed package from script raises “AttributeError: module has no attribute” or “ImportError: cannot import name”

I have a script named requests.py that imports the requests package. The script either can't access attributes from the package, or can't import them. Why isn't this working and how do I fix it? ...
680
votes
24answers
493k views

How do you remove duplicates from a list whilst preserving order?

Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can ...
689
votes
8answers
495k views

How to iterate through two lists in parallel?

I have two iterables in Python, and I want to go over them in pairs: foo = (1, 2, 3) bar = (4, 5, 6) for (f, b) in some_iterator(foo, bar): print "f: ", f, "; b: ", b It should result in: f: 1;...
256
votes
9answers
209k views

Syntax error on print with Python 3 [duplicate]

Why do I receive a syntax error when printing a string in Python 3? >>> print "hello World" File "<stdin>", line 1 print "hello World" ^ SyntaxError: ...
93
votes
1answer
15k views

Why does `a == b or c or d` always evaluate to True?

I am writing a security system that denies access to unauthorized users. import sys print("Hello. Please enter your name:") name = sys.stdin.readline().strip() if name == "Kevin" or "Jon" or "Inbar":...
2362
votes
22answers
547k views

Difference between __str__ and __repr__?

What is the difference between __str__ and __repr__ in Python?
2541
votes
17answers
468k views

How to make a chain of function decorators?

How can I make two decorators in Python that would do the following? @makebold @makeitalic def say(): return "Hello" ...which should return: "<b><i>Hello</i></b>" I'm ...
140
votes
6answers
14k views

Why is the order in dictionaries and sets arbitrary?

I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order. I mean, it's a programming language so everything in the language must be 100% determined, correct? ...
1304
votes
14answers
1.7m views

Select rows from a DataFrame based on values in a column in pandas

How to select rows from a DataFrame based on values in some column in pandas? In SQL I would use: select * from table where colume_name = some_value. I tried to look at pandas documentation but ...
1816
votes
22answers
2.4m views

Converting string into datetime

Short and simple. I've got a huge list of date-times like this as strings: Jun 1 2005 1:33PM Aug 28 1999 12:00AM I'm going to be shoving these back into proper datetime fields in a database so I ...
3874
votes
44answers
1.5m views

How to merge two dictionaries in a single expression?

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of ...
1110
votes
14answers
330k views

What is the meaning of a single and a double underscore before an object name?

Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also, explain the difference between a single and a double leading underscore. Also, does ...
176
votes
11answers
517k views

input() error - NameError: name '…' is not defined

I am getting an error when I try to run this simple python script: input_variable = input ("Enter your name: ") print ("your name is" + input_variable) Lets say I type in "dude", the error I am ...
2000
votes
35answers
3.2m views

How to read a file line-by-line into a list?

How do I read every line of a file in Python and store each line as an element in a list? I want to read the file line by line and append each line to the end of the list.
1008
votes
14answers
1.4m views

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

I've got a Python program where two variables are set to the value 'public'. In a conditional expression I have the comparison var1 is var2 which fails, but if I change it to var1 == var2 it returns ...
1615
votes
26answers
1.7m views

How to print without newline or space?

The question is in the title. I'd like to do it in python. What I'd like to do in this example in c: #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); ...
383
votes
14answers
236k views

Convert string representation of list to list

I was wondering what the simplest way is to convert a string list like the following to a list: x = u'[ "A","B","C" , " D"]' Even in case user puts spaces in between the commas, and spaces inside of ...