All Questions

1882
votes
30answers
103053 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 ...
321
votes
14answers
85863 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 ...
1977
votes
27answers
988375 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...
324
votes
11answers
201632 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...
344
votes
13answers
15068 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...
1447
votes
16answers
851814 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?
171
votes
12answers
74595 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 ...
1378
votes
55answers
532905 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...
1894
votes
22answers
854384 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_...
624
votes
18answers
279945 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