h8t4nk
h8t4nk

Reputation: 77

Comparing and substitution of opposite

I have a list with two items and I want c to equal the opposite of b?

a = ['rzz2', 'rzz3']
b = 'rzz2'

How can I get c to hold 'rzz3'?

Upvotes: 1

Views: 56

Answers (4)

user2555451
user2555451

Reputation:

Because the list only has two items, a simple conditional expression will work fine:

>>> a = ['rzz2', 'rzz3']
>>> b = 'rzz2'
>>> c = a[0] if a[0] != b else a[1]
>>> c
'rzz3'
>>>

Performance-wise, this is the fastest solution:

>>> from timeit import timeit
>>> a = ['rzz2', 'rzz3']
>>> b = 'rzz2'
>>> timeit('a[0] if a[0] != b else a[1]', 'from __main__ import a, b')
0.45458095931186787
>>> timeit('a[1 - a.index(b)]', 'from __main__ import a, b')
1.0331033692829674
>>> timeit('{b}.symmetric_difference(a)', 'from __main__ import a, b')
0.9464230789108647
>>> timeit('[i for i in a if i!=b][0]', 'from __main__ import a, b')
2.0873136110874384
>>>

Upvotes: 2

corn3lius
corn3lius

Reputation: 4985

c = a[1 - a.index(b)]

if its always a list of two ...

Upvotes: 3

Jon Clements
Jon Clements

Reputation: 142156

I'd be tempted to go for a set here, which may return zero or more results...

a = ['rzz2', 'rzz3']
b = 'rzz2'
print {b}.symmetric_difference(a)
# set(['rzz3'])

Upvotes: 5

inspectorG4dget
inspectorG4dget

Reputation: 113955

In [201]: a = ['rzz2', 'rzz3']

In [202]: b = 'rzz2'

In [203]: c = [i for i in a if i!=b][0]

In [204]: c
Out[204]: 'rzz3'

In [205]: c = a[1]

In [206]: c
Out[206]: 'rzz3'

Upvotes: 0

Related Questions