All Questions

1976
votes
27answers
987777 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...
344
votes
13answers
15062 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...
1446
votes
16answers
851111 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?
1378
votes
55answers
532568 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...
1732
votes
29answers
940288 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 ...
317
votes
37answers
82704 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 desi...
101
votes
6answers
98666 views

How do I make a list of data frames?

How do I make a list of data frames and how do I access each of those data frames from the list? I can't find a simple example of this anywhere. SO is telling me my post is too short, so I'll get th...
54
votes
4answers
26296 views

Why does my ArrayList contain N copies of the last item added to the list?

I'm adding three different objects to an ArrayList, but the list contains three copies of the last object I added. For example: for (Foo f : list) { System.out.println(f.getValue()); } Expe...
552
votes
33answers
426026 views

How do you remove duplicates from a list in 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...
179
votes
10answers
100063 views

Get the cartesian product of a series of lists?

How can I get the Cartesian product (every possible combination of values) from a group of lists? Input: somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] Desired output: [(1, 'a', 4), (1, ...

Previous Next