I was just trying to shorten a code snippet in python and came across the strange way of working of the following code.  sample = [[]] * 3  # OUTPUT - [[], [], []] - Simple enough to understand  sample[0].append(1)  # OUTPUT - [[1],[1],[1]] - Why is this happening?  sample[1].append(2)   # OUTPUT - [[1,2],[1,2],[1,2]] - Why is this happening?  sample[2].append(3)   # OUTPUT - [[1,2,3],[1,2,3],[1,2,3]] - Why is this happening?   Why is appending to a nested list appending to all the nested lists in the list?   Are all the nested lists pointing to one list? If so where is the original copy of the list?
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?
19281
Consider the following piece of Markdown code:  This is some regular text.      &gt;&gt;&gt; def factorial(n):     ...     return 1 if n &lt; 2 else n * factorial(n - 1)     ...   * This is a list item.      &gt;&gt;&gt; def factorial(n):     ...     return 1 if n &lt; 2 else n * factorial(n - 1)     ...    Notice that the second code block is preceded by a list item.   Why is the factorial code not properly formatted under these circumstances? To demonstrate the problem, I'll insert the Markdown code show above:    This is some regular text.  &gt;&gt;&gt; def factorial(n): ...     return 1 if n &lt; 2 else n * factorial(n - 1) ...     This is a list item                 def factorial(n):       ...     return 1 if n &lt; 2 else n * factorial(n - 1)       ...               This applies to numbered as well as unnumbered lists.
60559
Is there is any difference between these two.  [[ $a == z* ]]   and   [ $a == z* ]    Can I have an example where they would have different outputs?  Furthermore, how does the working of [[ ]] differs from [ ]?
106
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.
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.
1520
I could swear I've seen the function (or method) that takes a list, like this [3, 7, 19] and makes it into iterable list of tuples, like so: [(0,3), (1,7), (2,19)] to use it instead of:  for i in range(len(name_of_list)):     name_of_list[i] = something   but I can't remember the name and googling "iterate list" gets nothing.
2695
Some of you may recognize this as Project Euler's problem number 11. The one with the grid.  I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why  grid = [  [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ], [ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ], ...   And I get this error:     File "D:\development\Python\ProjectEuler\p11.py", line 3     [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ],        ^ SyntaxError: invalid token   Why is it throwing an error before the comma?
76488
I have heard/read the term but don't quite understand what it means.  When should I use this technique and how would I use it? Can anyone provide a good code sample?
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:
12929
Could someone please tell me what I'm doing wrong with this code? It is just printing 'count' anyway.  I just want a very simple prime generator (nothing fancy).   import math  def main():     count = 3     one = 1     while one == 1:         for x in range(2, int(math.sqrt(count) + 1)):             if count % x == 0:                  continue             if count % x != 0:                 print count          count += 1
98138
In Python, I can do:  &gt;&gt;&gt; list = ['a', 'b', 'c'] &gt;&gt;&gt; ', '.join(list) 'a, b, c'   Is there any easy way to do the same when I have a list of objects?  &gt;&gt;&gt; class Obj: ...     def __str__(self): ...         return 'name' ... &gt;&gt;&gt; list = [Obj(), Obj(), Obj()] &gt;&gt;&gt; ', '.join(list) Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: sequence item 0: expected string, instance found   Or do I have to resort to a for loop?
17001
I'm wondering where I find the source to show how the operator ** is implemented in Python.  Can someone point me in the right direction?
4181
What's the best way to break from nested loops in Javascript?  //Write the links to the page. for (var x = 0; x &lt; Args.length; x++) {    for (var Heading in Navigation.Headings)    {       for (var Item in Navigation.Headings[Heading])       {          if (Args[x] == Navigation.Headings[Heading][Item].Name)          {             document.write("&lt;a href=\""                 + Navigation.Headings[Heading][Item].URL + "\"&gt;"                 + Navigation.Headings[Heading][Item].Name + "&lt;/a&gt; : ");             break; // &lt;---HERE, I need to break out of two loops.          }       }    } }
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?
10523
I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful.
18727
This question is somewhat of a follow up to an answer to a previous question ().  I would like to create a list environment (similar to itemize and enumerate) such that the output of the list environment is a comma-separated list.  For example, the following input:  \begin{commalist}     \item Item A     \item Item B     \item Item C \end{commalist}   Should produce the following output:  Item A, Item B and Item C.   Additionally, it would be nice to be able to specify the use of a comma instead of the final and (so that the output is instead Item A, Item B, Item C..
28573
I want to make an enumerated list in the following format:  [1] foo foo [2] foo foo ...    How I can do that using enumerated lists? I have tried the following:  \begin{enumerate}[\left[ 1 \right]]   but it does not work.