I have a list of tuples like this:
[('foo','bar'),('foo1','bar1'),('foofoo','barbar')]
What is the fastest way in python (running on a very low cpu/ram machine) to swap values like this...
[('bar','foo'),('bar1','foo1'),('barbar','foofoo')]
I am currently using:
for x in mylist:
self.my_new_list.append(((x[1]),(x[0])))
Is there a better or faster way???
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
The simplest way to swap the values of two variables is using a temp variable. The temp variables is used to store the value of the fist variable ( temp = a ). This allows you to swap the value of the two variables ( a = b ) and then assign the value of temp to the second variable.
Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.
To swap two list elements x and y by value, get the index of their first occurrences using the list. index(x) and list. index(y) methods and assign the result to variables i and j , respectively. Then apply the multiple assignment expression lst[i], lst[j] = lst[j], lst[i] to swap the elements.
You could use map:
map (lambda t: (t[1], t[0]), mylist)
Or list comprehension:
[(t[1], t[0]) for t in mylist]
List comprehensions are preferred and supposedly much faster than map when lambda is needed, however note that list comprehension has a strict evaluation, that is it will be evaluated as soon as it gets bound to variable, if you're worried about memory consumption use a generator instead:
g = ((t[1], t[0]) for t in mylist)
#call when you need a value
g.next()
There are some more details here: Python List Comprehension Vs. Map
You can use reversed
like this:
tuple(reversed((1, 2)) == (2, 1)
To apply it to a list, you can use map
or a list/generator comprehension:
map(tuple, map(reversed, tuples)) # map
[tuple(reversed(x)) for x in tuples] # list comprehension
(tuple(reversed(x)) for x in tuples) # generator comprehension
If you're interested primarily in runtime speed, I can only recommend that you profile the various approaches and pick the fastest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With