All Questions

1853
votes
30answers
101199 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 ...
310
votes
14answers
83239 views

How do I 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 ...
1932
votes
26answers
966780 views

Understanding Python's 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...
314
votes
10answers
194260 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 >= 1...
1416
votes
16answers
827487 views

How to clone or copy a list?

What are the options to clone or copy a list in Python? Using new_list = my_list then modifies new_list every time my_list changes. Why is this?
332
votes
13answers
14617 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 t...
1865
votes
22answers
836197 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 __init_...
1352
votes
54answers
521305 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...
165
votes
12answers
72700 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 ...
615
votes
18answers
273237 views

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...

Previous Next