Python separating the result of combinations

Question:

I have the following code I took from Geeksforgeeks.org to obtain combinations of a list:

from itertools import combinations

def comb(lper,n):
# A Python program to print all
# combinations of given length
 
# Get all combinations of list
# and length n
    b = combinations(lper, n)

    return b

lper = [i for i in range(-999,1000)]

lcomb = list(comb(lper,2))
print(lcomb)

This returns me

"[(-999, -998), (-999, -997), (-999, -996), (-999, -995), (-999, -994), (-999, -993)...]"

When I try to assign each number of a pair to a variable:

for i in lcomb:
    a = lcomb[i][0]
    b = lcomb[i][1]

I get the error

"TypeError: list indices must be integers or slices, not tuple"

I read the documentation of tuples and it is how we iterate through them. Am I not able to list a tuple of a list?
Sorry if this has been covered, I was not able to find it anywhere.

Asked By: Believe82

||

Answers:

You are indexing the list with each tuple, for example in the first iteration it would be:

a = lcomb[(-999, -998)][0]
b = lcomb[(-999, -998)][1]

This is of course not working. I think you were assuming i is the index. To make it work that way, use:

for i in range(len(lcomb)):
    a = lcomb[i][0]
    b = lcomb[i][1]

If it’s only about accessing the first and second element of each tuple in the list, you could simply use:

for a, b in lcomb:
    # do something here
Answered By: Erik Fubel

You can use enumerate function. Like this

for i, lcomb_tuple in enumerate(lcomb):
  ...

"i" is an index in lcomb list.
"lcomb_tuple" is a tuple from lcomb.
If you don’t need the lcomb_tuple, you can replace it to "_" like that:

for i, _ in enumerate(lcomb):
  ...
Answered By: Dmitrii Malygin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.