list_a = [1,7,9,35,36,37] list_b = [3,4,5,40]   Expected output:  list_merged = [1,3,4,5,7,9,35,36,37,40]   Condition : must traverse both list only once  I know of zip which works as below and does quite fit in my requirement.  &gt;&gt;&gt; x = [1, 2] &gt;&gt;&gt; y = [1, 3, 4, 5, 6] &gt;&gt;&gt; zip(x,y) [(1, 1), (2, 3)] &gt;&gt;&gt; zip(y, x) [(1, 1), (3, 2)]
64496
I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?
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?
1083
Is there a simple way to flatten a list of iterables with a list comprehension, or failing that, what would you all consider to be the best way to flatten a shallow list like this, balancing performance and readability?  I tried to flatten such a list with a nested list comprehension, like this:  [image for image in menuitem for menuitem in list_of_menuitems]   But I get in trouble of the NameError variety there, because the name 'menuitem' is not defined.  After googling and looking around on Stack Overflow, I got the desired results with a reduce statement:  reduce(list.__add__, map(lambda x: list(x), list_of_menuitems))   But this method is fairly unreadable because I need that list(x) call there because x is a Django QuerySet object.  Conclusion:   Thanks to everyone who contributed to this question.  Here is a summary of what I learned.  I'm also making this a community wiki in case others want to add to or correct these observations.  My original reduce statement is redundant and is better written this way:  &gt;&gt;&gt; reduce(list.__add__, (list(mi) for mi in list_of_menuitems))   This is the correct syntax for a nested list comprehension (Brilliant summary !):  &gt;&gt;&gt; [image for mi in list_of_menuitems for image in mi]   But neither of these methods are as efficient as using itertools.chain:  &gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; list(chain(*list_of_menuitems))   And as @cdleary notes, it's probably better style to avoid * operator magic by using chain.from_iterable like so:  &gt;&gt;&gt; chain = itertools.chain.from_iterable([[1,2],[3],[5,89],[],[6]]) &gt;&gt;&gt; print(list(chain)) &gt;&gt;&gt; [1, 2, 3, 5, 89, 6]
97052
The typical ConfigParser generated file looks like:  [Section] bar=foo [Section 2] bar2= baz   Now, is there a way to index lists like, for instance:  [Section 3] barList={     item1,     item2 }   Related question:
96772
This is a continued discussion from () by return count only.     Problem      Given four lists A, B, C, D of integer values, compute how many tuples   (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.      To make problem a bit easier, all A, B, C, D have same length of N   where \$0 \le N \le 500\$. All integers are in the range of \$-2^{28}\$ to \$2^{28} - 1\$   and the result is guaranteed to be at most \$2^{31} - 1\$.      Example:      Input:  A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2]       Output:  2       Explanation:      The two tuples are:         (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0   (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0      I'm wondering if there are any ideas to have a solution less than \$O(n^2)\$ time complexity.  Source code in Python 2.7,  from collections import defaultdict def four_sum(A, B, C, D):     sum_map = defaultdict(int)     result = 0     for i in A:         for j in B:             sum_map[i+j] += 1     for i in C:         for j in D:             if -(i+j) in sum_map:                 result += sum_map[-(i+j)]      return result  if __name__ == "__main__":     A = [1, 2]     B = [-2, -1]     C = [-1, 2]     D = [0, 2]     print four_sum(A,B,C,D)
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?
113672
For example:  &gt;&gt;&gt; x = [1, 1, 2, 'a', 'a', 3] &gt;&gt;&gt; unique(x) [1, 2, 'a', 3]   Assume list elements are hashable.  Clarification: The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].
111448
I have two iterators, a list and an itertools.count object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:  &gt;&gt;&gt; import itertools &gt;&gt;&gt; c = itertools.count(1) &gt;&gt;&gt; items = ['foo', 'bar'] &gt;&gt;&gt; merged = imerge(items, c)  # the mythical "imerge" &gt;&gt;&gt; merged.next() 'foo' &gt;&gt;&gt; merged.next() 1 &gt;&gt;&gt; merged.next() 'bar' &gt;&gt;&gt; merged.next() 2 &gt;&gt;&gt; merged.next() Traceback (most recent call last):     ... StopIteration   What is the simplest, most concise way to do this?
1704
This has always confused me. It seems like this would be nicer:  my_list = ["Hello", "world"] print(my_list.join("-")) # Produce: "Hello-world"   Than this:  my_list = ["Hello", "world"] print("-".join(my_list)) # Produce: "Hello-world"   Is there a specific reason it is like this?
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 ?
106249
I have three files 1.zip, 1.z01 1.z02. I would like to extract and join them into a file, by right clicking 1.zip and selecting "Extract Here". But then there comes an error:     7-Zip 9.04 beta  Copyright (c)   1999-2009 Igor Pavlov  2009-05-30   p7zip Version 9.04   (locale=en_US.utf8,Utf16=on,HugeFiles=on,2   CPUs)      Error: /home/tim/Desktop/1.zip:   Can not open file as archive      Errors: 1   I was wondering what the problem it is and how I can solve it?  Thanks and regards!    ADDED: Is my usage of "unzip -FF" wrong? It seems not work:  $ unzip -FF 1.zip  Archive:  1.zip warning [1.zip]:  zipfile claims to be last disk of a multi-part archive;   attempting to process anyway, assuming all parts have been concatenated   together in order.  Expect "errors" and warnings...true multi-part support   doesn't exist yet (coming soon). file #1:  bad zipfile offset (local header sig):  0   Thanks again!  2nd ADDED: Still ain't right.  $ cat 1.z01 1.z02 1.zip &gt; combined.zip &amp;&amp; unzip -FF combined.zip Archive:  combined.zip warning [combined.zip]:  zipfile claims to be last disk of a multi-part archive;   attempting to process anyway, assuming all parts have been concatenated   together in order.  Expect "errors" and warnings...true multi-part support   doesn't exist yet (coming soon). warning [combined.zip]:  209829313 extra bytes at beginning or within zipfile   (attempting to process anyway) file #1:  bad zipfile offset (local header sig):  209829313   (attempting to re-compensate)  extracting: 1.wmv   bad CRC ee181eef  (should be f3c61875)   It generated 1.wmv, which can play well only until  midway in Gnome Mplayer.  3rd ADDED: Am I using 7z wrongly:  $ 7z e 1.z01  7-Zip 9.04 beta  Copyright (c) 1999-2009 Igor Pavlov  2009-05-30 p7zip Version 9.04 (locale=en_US.utf8,Utf16=on,HugeFiles=on,2 CPUs)  Processing archive: 1.z01  Error: Can not open file as archive  $ 7z e 1.zip  7-Zip 9.04 beta  Copyright (c) 1999-2009 Igor Pavlov  2009-05-30 p7zip Version 9.04 (locale=en_US.utf8,Utf16=on,HugeFiles=on,2 CPUs)  Processing archive: 1.zip  Error: Can not open file as archive
467
How do you generate all the permutations of a list in Python, independently of the type of elements in that list?  For example:  permutations([]) []  permutations([1]) [1]  permutations([1, 2]) [1, 2] [2, 1]  permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1]
122930
I'm comparing two list given in the list to see if the item.name exists in both for loop. If not then add into a list to show the error for the missing names.  set&lt;id&gt; setAssetIds = new set&lt;id&gt;(); list&lt;Asset_Store__c&gt;  assets = [select id,name......]; for(Asset_Store__c item : assets ) {     setAssetIds.add(item.id);  }   list&lt;Meter__c&gt;  meters = [select id,name......where id in : setAssetIds];  //now comparing the two lists for(Asset_Store__c a : assets) {    for(Meter__c m : meters)    {      if(a.Name != m.Name)      {        //not matched...        break;      }     } }   the problem with the above approach is that, its not finding the correct name.
11629
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].  I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
78279
I'm sure there's a simpler way of doing this that's just not occurring to me.  I'm calling a bunch of methods that return a list.  The list may be empty.  If the list is non-empty, I want to return the first item; otherwise, I want to return None.  This code works:  my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None   It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it.  Is there?  Edit:  The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:  x = get_first_list() if x:     # do something with x[0]     # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y:     # do something with y[0]     # inevitably forget the [0] part AGAIN, and have another bug to fix   What I'd like to be doing can certainly be accomplished with a function (and probably will be):  def first_item(list_or_none):     if list_or_none: return list_or_none[0]  x = first_item(get_first_list()) if x:     # do something with x y = first_item(get_second_list()) if y:     # do something with y   I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick.  But seeing these answers, it seems like a function is the simple solution.
52341
I'm trying to find an efficient algorithm for the following problem:  Given two different sets, both of size $N$. Each element in the two sets has coordinates $(x,y)$. The task is to optimize the pairings between these two sets such that the maximum distance between the paired elements given a pairing, is minimized. I have only found algorithms that deal with the squared sum of all distances between paired elements or the smallest distance between any two points from the two different sets.  For example: Given a list of $N$ pair of points that are associated with locations $(x_0,y_0), (x_1,y_1), (x_2,y_2),\dotsc,( x_{n-1},y_{n-1})$, name them $a_0,a_1,a_2,\dotsc,a_{N-1}$ accordingly. And another list of $N$ pairs of different points (locations) $(x_0,y_0), (x_1,y_1), (x_2,y_2),\dotsc,( x_{n-1},y_{n-1})$, name them $b_0,b_1,b_2,\dotsc,b_{N-1}$ accordingly. How can I pair all elements (each element is a pair of points) from list 1 $(a_0,a_1,a_2\dotsc,a_{N-1})$ to the other elements in list 2 $(b_0,b_1,b_2,\dotsc,b_{N-1})$ so that we chose the shortest distances? eventually, I'd need to print the maximum distance among all minimum distances (that we have found for each of the elements). Any idea how can this be achieved in reasonable run time? or name an algorithm that might help here.
113483
I have a list A with columns Emp ID, First name &amp; last name and list B wih column name Emp ID, First name, last name , phone number and address.  I want functionality such that when i enter item in List A and save same data should get copied in 3 columns of list B. Can someone help me with the approach. Thnks