0

in PYTHON i have one list and i want to make from it a multiple lists, for every item i want him to create a list with the other items

my initial list :

cities = ['Chevalley', 'A.Gharmoul 1', 'El Madania']

then i want the output to be :

[
  ['Chevalley', 'A.Gharmoul 1'],
  ['Chevalley','El Madania'],
  ['A.Gharmoul 1', 'El Madania']
]
ilyesBourouba
  • 101
  • 10
  • itertools might help you out. https://docs.python.org/3/library/itertools.html#itertools.combinations look at this documentation – Ganesh Tiwari Oct 27 '20 at 12:20
  • 1
    Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Tomerikoo Oct 27 '20 at 12:25
  • @ilyesBourouba Let me know, what do you think of my answer. Now I am planning to delete my answers which are not useful for the question (No upvotes answers) – Sivaram Rasathurai Nov 01 '20 at 02:54

6 Answers6

1

The below code will help you to create the resultant list you are looking for:

items = ['Chevalley', 'A.Gharmoul 1', 'El Madania']
res = [[items[i],items[j]] for i in range(len(items)) for j in range(i+1, len(items))]
print(res)
Ananth
  • 787
  • 5
  • 18
1
result_list = []
for i in ['Chevalley', 'A.Gharmoul 1', 'El Madania']:
    for j in ['Chevalley', 'A.Gharmoul 1', 'El Madania']:
        if i != j:
            result_list.append([i, j])

It should iterate over every possible pairing while ignoring pairing element with itself.

0

while this isn't the same it is pretty close to what you are looking for.

import itertools
a = ['Chevalley', 'A.Gharmoul 1', 'El Madania']
result = list(itertools.combinations(a,2)) # number is the amount of items you want in the resultant tuple

result will have tuples of length 2 in a list.

Ganesh Tiwari
  • 176
  • 2
  • 17
0

Below should do it:

l  = ['Chevalley', 'A.Gharmoul 1', 'El Madania']
n = [[l[i], l[j]] for i in range(0, len(l) - 1, 1) for j in range(i + 1, len(l), 1)]

n will equate to:

[['Chevalley', 'A.Gharmoul 1'],
 ['Chevalley', 'El Madania'],
 ['A.Gharmoul 1', 'El Madania']]
Dev
  • 665
  • 1
  • 4
  • 12
0

nested for loops does your work

list1 =['Chevalley', 'A.Gharmoul 1', 'El Madania']

output =[]

for i in range(len(list1)):
 for j in range(i+1,len(list1)):
  output.append([list1[i],list1[j]]) 

print(output)#[['Chevalley', 'A.Gharmoul 1'],['Chevalley','El Madania',['A.Gharmoul 1', 'El Madania']]
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45
0

You can use itertools and convert the output tuples into lists:

import itertools

new = [ list(el) for el in itertools.combinations(['Chevalley', 'A.Gharmoul 1', 'El Madania'], 2) ]
hasleron
  • 499
  • 3
  • 10