subixonfire subixonfire - 1 year ago 99
Python Question

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

I have a tuple/list inside a list like this:


What is the fastest way in python (running on a very low cpu/ram machine) to swap values like this...


curently using:

for x in mylist:

Is there a better or faster way???

mux mux
Answer Source

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

There are some more details here: Python List Comprehension Vs. Map