In the code below, very strangely to me, 0 and 1 are added to the BOTH keys:  zip_to_dict1 = zip(["a", "b"], [[]]*2) dict1 = dict(zip_to_dict1) dict1["a"].append(0) dict1["b"].append(1) print(dict1["a"], dict1["b"]) # [0, 1] [0, 1]   However, this works somehow:  zip_to_dict2 = zip(["a", "b"], [[], []]) dict2 = dict(zip_to_dict2) dict2["a"].append(0) dict2["b"].append(1) print(dict2["a"], dict2["b"]) # [0] [1]   Is there any difference between [[]]*2 and [[], []]?:  [[]]*2 == [[], []] # True   ...What's the problem?  (Note: I'm using Python 3.4.1)
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?
122421
There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join  I tried the following: concatenating two strings as part of a directory path: three approaches:   '+' which i should not do str.join os.path.join   Here is my code:  import os,time  s1='/part/one/of/dir' s2='part/two/of/dir' N=10000  t=time.clock() for i in xrange(N):     s=s1+os.sep+s2 print time.clock()-t  t=time.clock() for i in xrange(N):     s=os.sep.join((s1,s2)) print time.clock()-t  t=time.clock() for i in xrange(N):     s=os.path.join(s1,s2) print time.clock()-t   Here the results (python 2.5 WinXP)  0.0182201927899 0.0262544541275 0.120238186697   Shouldn't it be exactly the other way round ?
5798
Is there any meaningful distinction between:  class A(object):     foo = 5   # some default value   vs.  class B(object):     def __init__(self, foo=5):         self.foo = foo   If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?
41227
A lot of times in Perl, I'll do something like this:  $myhash{foo}{bar}{baz} = 1   How would I translate this to Python? So far I have:  if not 'foo' in myhash:     myhash['foo'] = {} if not 'bar' in myhash['foo']:     myhash['foo']['bar'] = {} myhash['foo']['bar']['baz'] = 1   Is there a better way?
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?
556
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union).  The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place. &gt;&gt;&gt; x = {'a': 1, 'b': 2} &gt;&gt;&gt; y = {'b': 10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print(z) None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11}  How can I get that final merged dictionary in z, not x? (To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)
66500
I am currently self-studying introductory combinatorics by reading Introduction to combinatorial mathematics. I am currently in the first chapter, and I have a question regarding one of the examples. The question was asking to count the number of n-bit strings with an even number of zeros. The answer is of course $2^{n-1}$. The author gave 2 solutions. I however didn't completely understand what I think is the straightforward one. The solution I got was that he took out 1 bit, leaving $(n-1)$ bits, if the number of zeros is even in the $(n-1)$-bit number, then he will just append a 1, if not then he will append a zero. So in the end we just needed to count the number of $(n-1)$-bit strings. The other solution (the straightforward one) that I didn't understand examined the symmetry that half of the $2^n$ must have an even number of zeros, and the other half will have an odd number of zeros. I just don't get why this property must hold. I can understand that half of the $2^n$ numbers will have even parity, but I can't see how it holds for the parity of the number of zero or one bits. If anyone can show me how that property holds, I'd be very grateful. I'd also be interested to see different explanations and proofs if possible.  Thank you.
53456
What is the difference between:  some_list1 = [] some_list1.append("something")   and  some_list2 = [] some_list2 += ["something"]
1267
Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:  args = [3, 6] range(*args)            # call with arguments unpacked from a list   This is equivalent to:  range(3, 6)   Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?
12628
Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:  &gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2
2267
What's the difference between the list methods append() and extend()?
114683
# touch $$ # gzip $$ # gzip --test $$.gz # echo $? 0 # OUT=$(gzip --test $$.gz) # echo $OUT  # if [ -z $OUT ] ; then echo $$ ; fi 26521 # if [ -n $OUT ] ; then echo $$ ; fi 26521 #      from bash(1)      -z string           True if the length of string is zero.    string    -n string           True if the length of string is non-zero.    I'm confused, how is it zero and non-zero at the same time? How does one do check against if key has a value (using bash)?
5316
I have an NSDictionary (stored in a plist) that I'm basically using as an associative array (strings as keys and values).  I want to use the array of keys as part of my application, but I'd like them to be in a specific order (not really an order that I can write an algorithm to sort them into).  I could always store a separate array of the keys, but that seems kind of kludgey because I'd always have to update the keys of the dictionary as well as the values of the array, and make sure they always correspond.  Currently I just use [myDictionary allKeys], but obviously this returns them in an arbitrary, non-guaranteed order.  Is there a data structure in Objective-C that I'm missing?  Does anyone have any suggestions on how to more elegantly do this?
81320
I am trying to add key value pair in the below JSON object, but it is getting added in the wrong way, is there any way i can add to each object a new  key value pair, that will help me to complete the req. JSON as follow : var object =[       {          &quot;asdf&quot;:&quot;&quot;,          &quot;fdrtf&quot;:&quot;869966&quot;,          &quot;hdhfhfh&quot;:&quot;utytut&quot;,          &quot;Cat&quot;:&quot;A&quot;                 },       {          &quot;hjhj&quot;:&quot;&quot;,          &quot;hfhfhf&quot;:&quot;h&quot;,          &quot;hhfh&quot;:&quot;hfjfhdj&quot;,          &quot;cat&quot;:&quot;B&quot;                 },       {          &quot;hjhj&quot;:&quot;&quot;,          &quot;hfhfhf&quot;:&quot;h&quot;,          &quot;hhfh&quot;:&quot;hfjfhdj&quot;,          &quot;cat&quot;:&quot;B&quot;       } ]  code i am using to add the new key value pair : for (let i = 0; i &lt; object.length; i++) {             object[i]['ABC'] = [i];         }  Actually expected should be: var object =[       {          &quot;asdf&quot;:&quot;&quot;,          &quot;fdrtf&quot;:&quot;869966&quot;,          &quot;hdhfhfh&quot;:&quot;utytut&quot;,          &quot;Cat&quot;:&quot;A&quot;,          &quot;ABC&quot;: &quot;0&quot;                 },       {          &quot;hjhj&quot;:&quot;&quot;,          &quot;hfhfhf&quot;:&quot;h&quot;,          &quot;hhfh&quot;:&quot;hfjfhdj&quot;,          &quot;cat&quot;:&quot;B&quot;,          &quot;ABC&quot;: &quot;1&quot;                 },       {          &quot;hjhj&quot;:&quot;&quot;,          &quot;hfhfhf&quot;:&quot;h&quot;,          &quot;hhfh&quot;:&quot;hfjfhdj&quot;,          &quot;cat&quot;:&quot;B&quot;          &quot;ABC&quot;: &quot;2&quot;       } ]  the final value i am getting as below: [&quot;0&quot;:{          &quot;hjhj&quot;:&quot;&quot;,          &quot;hfhfhf&quot;:&quot;h&quot;,          &quot;hhfh&quot;:&quot;hfjfhdj&quot;,          &quot;cat&quot;:&quot;B&quot;,           },    &quot;1&quot;:{          &quot;asdf&quot;:&quot;&quot;,          &quot;fdrtf&quot;:&quot;869966&quot;,          &quot;hdhfhfh&quot;:&quot;utytut&quot;,          &quot;Cat&quot;:&quot;A&quot;              },    &quot;2&quot;:{        &quot;hjhj&quot;:&quot;&quot;,          &quot;hfhfhf&quot;:&quot;h&quot;,          &quot;hhfh&quot;:&quot;hfjfhdj&quot;,          &quot;cat&quot;:&quot;B&quot;    }   ]  kindly someone help me out to achieve this
2814
What's the best way to merge 2 or more dictionaries (Dictionary&lt;T1,T2&gt;) in C#? (3.0 features like LINQ are fine).  I'm thinking of a method signature along the lines of:  public static Dictionary&lt;TKey,TValue&gt;                  Merge&lt;TKey,TValue&gt;(Dictionary&lt;TKey,TValue&gt;[] dictionaries);   or  public static Dictionary&lt;TKey,TValue&gt;                  Merge&lt;TKey,TValue&gt;(IEnumerable&lt;Dictionary&lt;TKey,TValue&gt;&gt; dictionaries);   EDIT: Got a cool solution from JaredPar and Jon Skeet, but I was thinking of something that handles duplicate keys. In case of collision, it doesn't matter which value is saved to the dict as long as it's consistent.
110341
I have a dict where each key references an int value. What's the best way to sort the keys into a list depending on the values?
1436
Imagine that you have the following list. keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam']  What is the simplest way to produce the following dictionary? a_dict = {'name': 'Monty', 'age': 42, 'food': 'spam'}