user11054683
user11054683

Reputation:

How can I loop till certain range inside the list?

I have a list of 5000 words.

words=['asd','bsd',.........,'dbn']

I am trying to make the possible combinations of the words

comb = combinations(words,2)
for i in list(comb): 
  b=''.join(i)
  print(b)

How can I run the loop for the first 100 words combinations?

Upvotes: 1

Views: 34

Answers (2)

user2390182
user2390182

Reputation: 73460

You can use islice and combinations from the itertools module. The following will display the first 100 combinations of length 2:

from itertools import combinations, islice

for c in islice(combinations(words, 2), 100):
    print(c)

Note that both functions return lazy generators, so that not all combinations have to be generated first (which is what happens once you call list(comb...)).

Upvotes: 2

soulmerge
soulmerge

Reputation: 75704

There is this great module called itertools, which most probably has what you need. Example from the permutations function:

# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210

Upvotes: 0

Related Questions