-1

I have 2 identical lists a = [a1,a2,a3] b = [a1,a2,a3] What is a most effective way to iterate over these 2 list simultaneously while i am interesting only in combination of different elements from both lists despite order, i.e a1a2 and a1a3. Combinations a1a1, a2a2, a3a3, a2a1, a3a1 i am interesting to skip, but interesting keep iterators values avaliable.

Want to re phrase questions: interesting in possible combinations of 2 elements from list a = [a1,a2,a3]

Felix
  • 1,539
  • 8
  • 20
  • 35
  • Use `itertools.product`, perhaps, with an `if left == right: continue` to skip those where they're both the same. – jonrsharpe Sep 26 '16 at 11:10
  • 2
    @jonrsharpe can't it be as simple as `itertools.combination(a,2)` as both the list are identical and combination would automatically remove the duplicate ones – armak Sep 26 '16 at 11:11
  • 1
    @armak you could do it like that, but that doesn't *"iterate over these 2 list simultaneously"*. It depends what the OP's actually trying to achieve, which isn't entirely clear - if the two lists are *always* identical, it's not obvious why they have two to start with. – jonrsharpe Sep 26 '16 at 11:13
  • What is the point of having 2 identical lists? Why not just have 1 list? – Chris_Rands Sep 26 '16 at 11:17
  • @jonrsharpe i agree – armak Sep 26 '16 at 11:21

2 Answers2

3

Use combinations,

from itertools import combinations
for i in combinations(['a1','a2','a3'],2):
    print i
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

List comprehensions!

a = ['1', '2', '3']
b = ['1', '2', '3']

c = [i + j for i in a for j in b if j != i]
print(c)  # prints -> ['12', '13', '21', '23', '31', '32']

EDIT

if you consider a1a2 and a2a1 to be duplicates you can use some clever slicing to skip them like so:

c = [ia + ib for i, ia in enumerate(a) for ib in a[i+1:]]
print(c)  # prints -> ['12', '13', '23']

As you might notice, list b is not used in the second one.

Ma0
  • 15,057
  • 4
  • 35
  • 65