0

I have this list of two-value tuples

stake_odds=[(0, 1), (0, 2), (0, 5), (0, 10), (2, 1), (2, 2), **(2, 5)**, (2, 10), (5, 1), (5, 2), (5, 5), (5, 10), (10, 1), (10, 2), (10, 5), (10, 10)]

I have the following function where I want to put the tuple into an object method where it calculates the product (or minus product depending on the instance) of the two numbers in the tuple. If the product is positive, I want to append the tuple used to another list, pos_cases.

def function():
    pos_cases=[]
    x,y=stake_odds[9]
    b1=bet1.payout(x,y)
    if b1 > 0:
        return b1, "b is greater than zero!"
        pos_cases.append(stake_odds[9])
        print(pos_cases)

print(function())

As you can see below I have to unpack the tuple into two variables before computing. I can do it by specifying the element of the list (stake_odds[9]), however I am looking for a way to generalize and loop through the list (stake_odds[i]) rather than going one by one.

The list in this example would be shortened to the following:

pos_cases =[(2, 1), (2, 2), (2, 5), (2, 10), (5, 1), (5, 2), (5, 5), (5, 10), (10, 1), (10, 2), (10, 5), (10, 10)]

How could I do this? The only thing I can think of is some nested for loop like:

for i in stake_odds: 
    for x,y in i:
        return(x,y)

But this results in error >TypeError: cannot unpack non-iterable int object>.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Your last example pulls the integers out of the two-element tuple. `i` gets one tuple out of `stake_odds` on each iteration. Your next loop pulls the two elements out of `i`, one at a time (as two separate integers), hence the error. change `for x,y in i:` to simply `x,y=i` and it will unpack as expected. – RufusVS Jan 04 '21 at 03:26
  • thanks, worked a charm! any way to just print the final list once its done? Currently am getting a print for every time it appends...e.g. [(2, 1)], then [(2, 1), (2, 2)] and so on – python_beginner Jan 04 '21 at 22:51
  • I can't see the code you are running now, but you probably need to undent the print line. – RufusVS Jan 04 '21 at 23:13
  • yep the unindent worked, thanks again. I changed print statement to return to remove the 'none' when getting the function output – python_beginner Jan 05 '21 at 22:02

1 Answers1

0

Doesn't this work?:

def function():
    pos_cases=[]
    for x,y in stake_odds:
        b1=bet1.payout(x,y)
        if b1 > 0:
            return b1, "b is greater than zero!"
            pos_cases.append((x,y))
    return pos_cases

print(function())
RufusVS
  • 4,008
  • 3
  • 29
  • 40