All Questions

1797
votes
29answers
97830 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 ...
286
votes
16answers
76128 views

How do I test one variable against multiple values?

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 ...
1868
votes
25answers
923519 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...
293
votes
9answers
176890 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...
318
votes
13answers
13714 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...
1361
votes
13answers
774944 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?
1817
votes
22answers
803279 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_...
1293
votes
52answers
496637 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...
156
votes
11answers
69095 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 ...
1602
votes
25answers
852898 views

Making a flat list out of list of lists in Python

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

Previous Next