Swap values in a tuple/list inside a list in python?
Asked Answered
S

5

19

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

Subfamily answered 14/11, 2012 at 18:19 Comment(0)
A
21

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

Airlee answered 14/11, 2012 at 18:27 Comment(0)
J
14

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.

Jeri answered 19/2, 2016 at 17:39 Comment(0)
A
5

A fancy way:

[t[::-1] for t in mylist]
Applewhite answered 8/8, 2018 at 20:59 Comment(0)
A
3

Using a list comprehension I find more elegant and understandable to use separate variables instead of indices for a single variable as in the solution provided by @iabdalkader:

[(b, a) for a, b in mylist]
Apperception answered 8/3, 2019 at 11:26 Comment(0)
M
0

To modify the current list in-place, the most efficient way is:

my_list[:] = [(y, x)  for x, y in my_list]

It is assigning to the list slice, which covers the entire list, without creating an extra duplicate of the list in memory. See also this answer.

Melvinamelvyn answered 4/1, 2021 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.