3

So I got a list in python like this:

[1,2,3,4]

And I want the combinations between the number 3 with every number something like this:

[(1,3),(2,3),(3,4)]

Is there something I can use? I know there is something called itertools, but I'm kinda new so i'm not sure how to use it.

Thank you!

7
  • itertools combinations and permutations is well documented, with many samples on this site. Try it out Commented Mar 10, 2020 at 15:05
  • You should not need itertools for this. Commented Mar 10, 2020 at 15:06
  • do you want this output: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] ? Commented Mar 10, 2020 at 15:13
  • No exactly, just one position (in this case 3) to the other positions Commented Mar 10, 2020 at 15:16
  • the order of the elements matter ? (4,3) is fine ? as an element ? Commented Mar 10, 2020 at 15:27

4 Answers 4

1

You might want to use a list comprehension:

orig_list = [1,2,3,4]
[(entry, 3) for entry in orig_list if entry != 3] # [(1, 3), (2, 3), (4, 3)]

If you're not interested in duplicate values you can make it into a set:

orig_list = set([1,2,3,4])
[(entry, 3) for entry in orig_list if entry != 3] # [(1, 3), (2, 3), (4, 3)]
Sign up to request clarification or add additional context in comments.

2 Comments

usually you use _ as a variable if you do not want to use that variable
This is great it helped me a lot thank you!, what if I also want the other position? No just (1,3) but also (3,1)?
1

An easy way to do this is using a loop:

list2 = []
for x in list1:
     list2.append((x,3))
print(list2)

If you want to get rid of (3,3) use:

list2 = []
for x in list1:
     if x != 3:
          list2.append((x,3))
print(list2)

Comments

1

you could use list comprehension with itertools.combinations:

import itertools

[e for e in itertools.combinations([1,2,3,4], 2) if 3 in e]

output:

[(1, 3), (2, 3), (3, 4)]

even better you could use itertools.repeat:

from itertools import repeat

l = [1,2,3,4]
[(f, s) for f, s in zip(l, repeat(3)) if f != 3]

output:

[(1, 3), (2, 3), (4, 3)]

2 Comments

Note: This turns a O(n) problem into a O(n²) problem (n choose 2 is n * (n - 1) / 2 work); for every value you generate, you have to filter out ~n. Fine if the input is length 4, less so if it's length 1000.
my second solution is O(n) time complexity, should be just fine, maybe the fastest
0

You could use:

l = [1,2,3,4]
[(l[i], 3) for i in range(l.index(3))] + [(3, l[i]) for i in range(l.index(3)+1, len(l))]

which gives the output:

[(1, 3), (2, 3), (3, 4)]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.