Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap values in a tuple/list inside a list in python?

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???

like image 681
subixonfire Avatar asked Nov 14 '12 18:11

subixonfire


People also ask

Can we change value of list inside tuple in Python?

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.

How do you interchange tuple variables in Python?

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.

Can we swap elements in tuple?

Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.

How do you swap items in a list in Python?

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.


2 Answers

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

like image 84
iabdalkader Avatar answered Sep 27 '22 22:09

iabdalkader


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.

like image 27
Elliot Cameron Avatar answered Sep 27 '22 22:09

Elliot Cameron