DNZ
DNZ

Reputation: 37

Iterate and select every two elements of a list python

I have the list below and I am able to create some other lists using every 2 combinations like this:

my_list = ['cc','th','ab','ca','cd']
from itertools import combinations
combi_2 = list(combinations(my_list,2))
print(combi_2)

I got this result:

[('cc', 'th'), ('cc', 'ab'), ('cc', 'ca'), ('cc', 'cd'), ('th', 'ab'), ('th', 'ca'), ('th', 'cd'), ('ab', 'ca'), ('ab', 'cd'), ('ca', 'cd')]

Using a parser, I am able to remove the ( ) and have a long list like this:

combi_2 = ['cc', 'th', 'cc', 'ab', 'cc', 'ca', 'cc', 'cd', 'th', 'ab', 'th', 'ca', 'th', 'cd', 'ab', 'ca', 'ab', 'cd', 'ca', 'cd']

Now, I want to iterate and select every 2 elements of this new created list without combination. What I want is something like this as output:

['cc', 'th' ], ['cc', 'ab'],...

I tried using this code:

for i, j in(combi_2):
    print(i,j)

but what I get is something like this:

['c','p']

How to do this properly ?

Upvotes: 1

Views: 389

Answers (1)

Pygirl
Pygirl

Reputation: 13349

try:

[list(subset) for subset in combinations(my_list, 2)]

[['cc', 'th'],
 ['cc', 'ab'],
 ['cc', 'ca'],
 ['cc', 'cd'],
 ['th', 'ab'],
 ['th', 'ca'],
 ['th', 'cd'],
 ['ab', 'ca'],
 ['ab', 'cd'],
 ['ca', 'cd']]

Upvotes: 2

Related Questions