Ouwan12
Ouwan12

Reputation: 51

For element in list of tuples, return other element in tuple

Below is my code for a function that searches a list of tuples called pairs. Each tuple in the list is comprised of two elements.

The element given in the function (called item) could be in the 0 or 1 position of the tuple, but all the tuples in the list are composed of only 2 elements.

pairs = [('a','b'),('c','d'),('e','f'),('c','a')]

def connections(pairs, item):
    output = ''
    for j in pairs:
        if item in j:
            output = output + str(j)
    return (output)

Right now this code will pull out the entire tuple(s) that have the item within them.

I'd like to change this code to only return the other element in the tuple and to return it as a string instead of a tuple.

Upvotes: 0

Views: 2234

Answers (3)

Sharad
Sharad

Reputation: 10602

pairs = [('a','b'),('c','d'),('e','f'),('c','a')]

def connections(pairs, item):
    output = ''
    for j in pairs:
        if item in j:
            index = 1-j.index(item)
            output = output + str(j[index])
    return (output)

print(connections(pairs, 'c'))

Output:

da

Upvotes: 0

Tom Karzes
Tom Karzes

Reputation: 24052

This should do what you want:

def connection(pairs, item):
    return ''.join([p[1-p.index(item)] for p in pairs if item in p])

Here's some sample output:

>>> connection([('a','b'),('c','d'),('e','f'),('c','a')], 'a')
'bc'

Upvotes: 7

TigerhawkT3
TigerhawkT3

Reputation: 49318

Instead of checking for membership, check for equality.

def connections(pairs, item):
    output = ''
    for j in pairs:
        if item == j[0]:
            output += j[1]
        elif item == j[1]:
            output += j[0]
    return output

Note that I've streamlined the concatenation into augmented assignment and removed the unnecessary str() calls, as they are already strings. Or you could do it as follows:

def connections(pairs, item):
    return ''.join(j[0] if item==j[1] else j[1] if item==j[0] else '' for j in pairs)

Upvotes: 0

Related Questions