-2

I have a list l of stings from a to z generated by using l=list(string.ascii_lowercase).

I want to take one value from the list l and combine with all other values of list except that selected value. For eg. ab,ac.....az. Again take b and combine with all other values like ba,bb.....bz. I know there will be redundant combinations.

I have tried this

for i in range(0, len(l)): 
    for j in range(0,len(l.pop(i))):
        print (l[i],l[j])

I am getting 'list index out of range' error. Is there more optimized way of doing it ?

Somanshu
  • 1
  • 2
  • You keep popping from the list making it smaller but the index doesnt change, meaning eventually your index comes to one of the elements you popped hence the error. – Josip Juros Apr 11 '22 at 06:50
  • Does this answer your question? [How to generate all permutations of a list?](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list) – ti7 Apr 11 '22 at 06:52

2 Answers2

1
In [1]: import string, itertools

In [2]: combinations = list(itertools.combinations(string.ascii_lowercase, 2))

In [4]: combinations
Out[4]:
[('a', 'b'),
 ('a', 'c'),
 ('a', 'd'),
 ('a', 'e'),
 ('a', 'f'),
 ('a', 'g'),
 ('a', 'h'),
 ('a', 'i'),
 ('a', 'j'),
 ('a', 'k'),
 ('a', 'l'),
 ('a', 'm'),
 ('a', 'n'),
 ('a', 'o'),
 ('a', 'p'),
 ...]
Işık Kaplan
  • 2,815
  • 2
  • 13
  • 28
0
mylist = list(string.ascii_lowercase)
selected_value = 'b'
new_list = [selected_value+i for i in mylist if i != selected_value]