0

I'm having difficulty getting two parameters returned from a function as a tuple:

>>> ir7(41,7)

(966, 1023, 571, 396, 105, 2, 3)

If I want to get specified tuple I use this:

 >>> ir7(41,7)[0]

966

but what if I want to get 1st, 3rd and 4th element from the tuple. What is the correct syntax? Something like:

a,b,c= ir7(41,7)[1][3][4]

5 Answers 5

1

You can unpack the return values:

_, a, _, b, c, _, _ = ir(41, 7)

The _ indicates the value being assigned here are not important.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm using micropython not sure how it is in normal python but here _ is variable name too, it use memory still. I was hoping that there was a direct syntax calling this, but looks there is no method for that
You could delete the _ variable after. As written in other answers, manually choose the indexes you want by saving the result of the answer first.
1

Call the method only once to make it more efficient. After that, it's just a matter of tuple-assignment.

v = ir7(41,7)
a, b, c= v[1], v[3], v[4]

Comments

1

There is a convention for using _ as the name for variables that you don't actually want to use. Using this, you can do:

_, a, _, b, c = ir7(41, 7)

Alternatively, you can do:

value = ir7(41, 7)
a, b, c = value[1], value[3], value[4]

If the number of items to exclude is large, you definitely want the second option.

Comments

1

You could introduce slicing to slim the result down before assigning values as well:

a, _, b, c = ir7(41, 7)[1:4]

Even better you could use operator.itemgetter

from operator import itemgetter

a, b, c = itemgetter(1,3,4)(ir7(41, 7))

Comments

1

When you do ir7(41,7)[1][3][4] you essentially tries to get the 4:th element of the 3:rd element of the 1:st element of an object (basically a 4-dimensional list). Instead you should fetch them separately:

# Get all the values initially in a separate variable
values = ir7(41,7)
a, b, c = values[1], values[3], values[4]

Or I you can do it this way:

_, a, _ b, c = ir7(41,7)

By omitting the indexes you don't want with placeholder variables _

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.