Getting One Value from a Tuple

Getting one value from a tuple

You can write

i = 5 + tup()[0]

Tuples can be indexed just like lists.

The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.

Get item with value from tuple in python

You can search for a particular tuple in the results list by iterating over the list and checking the value of the second item of each tuple (which is your key):

results = [('object%d' % i, '111.111.5.%d' % i) for i in range(1,8)]

key = '111.111.5.4'
result = None
for t in results:
if t[1] == key:
result = t

print result

Output:


('object4', '111.111.5.4')

This demonstrates accessing an item in a tuple with a zero-based index (1 in this case means the second element). Your code will be more readable if you unpack the tuples in the for loop:

for obj, value in results:
if value == key:
result = (obj, value)

Your results might be more generally useful if you convert them to a dictionary:

>>> results_dict = {v:k for k,v in results}
>>> print results_dict['111.111.5.6']
object6
>>> print results_dict['111.111.5.1']
object1
>>> print results_dict['blah']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'blah'
>>> print results_dict.get('111.111.5.5')
object5
>>> print results_dict.get('123456')
None

Using dict.get() is close to the syntax that you requested in your question.

How to pass a specific value from Tuple into a function

In the code you provided you don't have a tuple you have a list. But it is still pretty much the same.

In your example lets say that you wanted to pass the first variable you would do it like this:

my_function(a_tuple[0])

If you don't understand why there is a zero here and how does this work I highly suggest learning about lists before functions.

Get value from Tuple

Assuming you have to work with a tuple and cannot change the data structure to a dict you can use the following:

MY_TUPLE_CHOICE = (
('INS', 'Instagram'),
('FAB', 'Facebook'),
('YOU', 'Youtube'),
('TWT', 'Twitter'),
)

def get_from_tuple(my_tuple, key):
return next((y for x, y in my_tuple if x == key), None)

print(get_from_tuple(MY_TUPLE_CHOICE, 'YOU')) # Youtube
print(get_from_tuple(MY_TUPLE_CHOICE, 'ASD')) # None

That said, note that the requirements of your task and the type of data you have are ideal for the use of a dictionary. In case you become allowed to use one, just convert your tuple with dict(MY_TUPLE_CHOICE).

How to get a singular value from a list of tuples?

Tuples are indexed the same way that lists are (their difference being that lists are mutable). So, if you have a list of tuples, you can access the individual elements the same way you would access the elements of a list.

For example,

>> x = [('a', 0), ('b', 1)]
>> x
[('a', 0), ('b', 1)]

>> type(x)
<class 'list'>

>> type(x[0])
<class 'tuple'>

>> type((x[0])[0]) # which is equivalent to
<class 'str'>

>> type(x[0][0])
<class 'str'>

>> x[0][0]
'a'

Therefore, if you need the ith element of a tuple that is the jth element of a list x, you access it with x[j][i].

Accessing a value in a tuple that is in a list

With a list comprehension.

[x[1] for x in L]

How to return a single value instead of a tuple?

If you know the function is always going to return a one-element tuple, you can use a one-element tuple assignment:

output, = fun(other_func())

or simply index:

output = fun(other_func())[0]

But in this case, a simple Don't do that, don't return a tuple might also apply:

output = other_func()

Get the first element of each tuple in a list in Python

Use a list comprehension:

res_list = [x[0] for x in rows]

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.

Extracting the a value from a tuple when the other values are unused

I think the usual way of doing it

x=foo[index]

Using _ is less common, and I think also discouraged. Using _ is also unwieldy when you need only a few elements out of a long tuple/list. Slicing also comes handy when you are only choosing a contiguous subsequence.

But at the end of the day I think it is just a matter of subjective preference. Use whatever that looks more readable to you and your team.



Related Topics



Leave a reply



Submit