I have a list of empty lists as such:  some_lists = [[]] * 3 [[], [], []]   I want to append an integer to the first sublist:  some_lists[0].append(1)   But it appends the integer 1 to all the sublists and generates:  [[1], [1], [1]]   How do I append elements individually to the sublists?
410
I needed to create a list of lists in Python, so I typed the following: my_list = [[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 innermost values: my_list[0][0] = 5  Now my list looks like this: [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]    which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?
9898
Code like this often happens: l = [] while foo:     # baz     l.append(bar)     # qux  This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements. In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient. I understand that code like this can often be refactored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there an equivalent for us Python programmers?
1888
I want to do something like String.Format("[{0}, {1}, {2}]", 1, 2, 3) which returns:  [1, 2, 3]   How do I do this in Python?
98693
You can turn any element $n$ into a singleton set by adding braces, $\{n\}$. Is there an inverse to this operation, such that if I know the set is a singleton set I can easily reference its element?  For example, say I have the set $A = \{5,6,7,8\}$, and then some process that iteratively eliminates all but one element of $A$, and then I want to see what 10 plus the resulting element is, how could I write that?  The only way I can think of is by referencing the first element by its index, e.g., $10 + A_1$. Is there another way to do it though? In my case the elements of $A$ are already indices, so I would have to index an index, like $10 + x_{A_1}$. Which is not the worst thing in the world, I was just wondering if there is a better way.
42119
Consider any integer, suppose a number 3. We can break any such integer down into a sequence of 1's. So, we can write: $$ 3\equiv1+1+1 $$ 3 represents what we get when we add 1 to 1 to another 1. Conceptually, what I am getting confused with, is the fact that notionally, at least according to this definition, there is one unit at the beginning, to which we add another, and yet a third. There seems to be a sequence here, which would imply there being an order. Am I missing something obvious?
63961
Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.  Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:  def getPermutations(string, storage, prefix=""):    if len(string) == 1:       storage.append(prefix + string)   # &lt;-----    else:       for i in range(len(string)):          getPermutations(string[:i]+string[i+1:], storage, prefix+string[i])  storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation   (Please don't care about inefficiency, this is only an example.)  Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:  def getPermutations(string, prefix=""):    if len(string) == 1:       yield prefix + string             # &lt;-----    else:       for i in range(len(string)):          getPermutations(string[:i]+string[i+1:], prefix+string[i])  for permutation in getPermutations("abcd"):    print permutation   This code does not work (the function behaves like an empty generator).  Am I missing something? Is there a way to turn the above recursive algorithm into a generator without replacing it with an iterative one?
42368
I have a python list, say l  l = [1,5,8]   I want to write a sql query to get the data for all the elements of the list, say  select name from students where id = |IN THE LIST l|   How do I accomplish this?
59203
I have a the following dictionary:  IDictionary&lt;int, IList&lt;MyClass&gt;&gt; myDictionary    and I am wanting to get all the values in the dictionary as an IList....    Just to add a bit of a background as to how I've gotten into this situation....  I have a method that gets me a list of MyClass. I then have another method that converts that list into a dictionary where they key is the id for MyClass. Later on...and without access to that original list...I'm needing to obtain the original ungrouped list of MyClass.    When I pass myDictionary.Values.ToList() to a method that takes an IList I get a compile error that says that it can't convert from   System.Collections.Generic.List&lt;System.Collections.Generic.IList&lt;MyClass&gt;&gt;    to:  System.Collections.Generic.IList&lt;MyClass&gt;   Now, I can understand that its gone and added each of the groups of IList to the new list as separate elements of the list....but in this instance its not really what I'm after. I just want a list of all the values in the entire dictionary.  How then can I get what I'm after without looping through each of the key values in the dictionary and creating the list I want?
109666
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?  lst = ['one', 2, 3]  lst1 = list(lst)  lst2 = lst[:]  import copy lst3 = copy.copy(lst)
1360
I want to create a list of lambda objects from a list of constants in Python; for instance:  listOfNumbers = [1,2,3,4,5] square = lambda x: x * x listOfLambdas = [lambda: square(i) for i in listOfNumbers]   This will create a list of lambda objects, however, when I run them:  for f in listOfLambdas:     print f(),   I would expect that it would print  1 4 9 16 25   Instead, it prints:  25 25 25 25 25   It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.  EDIT: a bit more of trying things and such came up with this:  listOfLambdas = [] for num in listOfNumbers:     action = lambda: square(num)     listOfLambdas.append(action)     print action()   Prints the expected squares from 1 to 25, but then using the earlier print statement:  for f in listOfLambdas:     print f(),   still gives me all 25s. How did the existing lambda objects change between those two print calls?  Related question:
64302
I frequently find myself writing code like this:  List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 }; foreach (int i in list) {     Console.Write("{0}\t", i.ToString()); } Console.WriteLine();   Better would be something like this:  List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 }; Console.WriteLine("{0}\t", list);   I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block?
70618
So I was writing up a simple binary tree in Python and came across [...]  I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however   &gt;&gt;&gt; a [[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0] &gt;&gt;&gt; Keys(a)#With a+b [0, 1, 6, 8, 3, -4] &gt;&gt;&gt; Keys(a)#With [a,b] [8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]] &gt;&gt;&gt; Keys(a)[1]#?? [8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]     Version using a+b  def Keys(x,y=[]):     if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess     return y   version using [a,b]  def Keys(x,y=[]):     if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]     return y   So what exactly is [...]?
1457
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.  For example:  original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])   Is there a builtin function that does that?
34678
I've a List of this type List> that contains this  List&lt;int&gt; A = new List&lt;int&gt; {1, 2, 3, 4, 5}; List&lt;int&gt; B = new List&lt;int&gt; {0, 1}; List&lt;int&gt; C = new List&lt;int&gt; {6}; List&lt;int&gt; X = new List&lt;int&gt; {....,....};   I want to have all combinations like this  1-0-6 1-1-6 2-0-6 2-1-6 3-0-6   and so on.  According to you is This possibile to resolve using Linq?
29728
In other words, can I do something like  for() {     for {        for {        }     } }   Except N times? In other words, when the method creating the loops is called, it is given some parameter N, and the method would then create N of these loops nested one in another?  Of course, the idea is that there should be an "easy" or "the usual" way of doing it. I already have an idea for a very complicated one.
740
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 list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.  I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.  I was looking for something useful in itertools but I couldn't find anything obviously useful. Might've missed it, though.  Related question:
16381
I would want to do something like:  &gt;&gt;&gt; lst = [1, 2, 3, 4, 5] &gt;&gt;&gt; lst.find(lambda x: x % 2 == 0) 2 &gt;&gt;&gt; lst.findall(lambda x: x % 2 == 0) [2, 4]   Is there anything nearing such behavior in Python's standard libraries?  I know it's very easy to roll-your-own here, but I'm looking for a more standard way.