Tuple conversion in python to list

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Tuple conversion in python to list



I have a tuple like


a = (1,2,3,4).



Is it possible to change the tuple to


a = [('roll', 1),('roll',2),('roll', 3),('roll', 4)]





One does not simply "change the tuple." You can change the value of the name a to be the appropriate tuple, but tuples are immutable and cannot themselves be changed. In other words, you change a, not the tuple.
– Rory Daulton
yesterday


a


a




5 Answers
5



Simple list comprehension here -


a = [("roll", i) for i in a]



OP


[('roll', 1), ('roll', 2), ('roll', 3), ('roll', 4)]



More about list comprehension here





@nikolas your welcome, do see the edited answer
– ThatBird
yesterday



Yes - simply do a list comprehension:


a = [('roll', i) for i in a]



Note that doing this will rebind a! (See the note by @ShadowRanger.)


a





Technically, it rebinds a; if a is aliased elsewhere under a different name, that alias is unchanged (e.g. b = a; a = [('roll', i) for i in a] will preserve the original value of a, accessible through the b alias). Subtle distinction, but important in some cases. Since a is initially bound to a tuple, it's not possible to mutate the tuple itself.
– ShadowRanger
yesterday




a


a


b = a; a = [('roll', i) for i in a]


a


b


a


tuple


tuple





Thanks, @ShadowRanger! That's very informative - I've edited my answer to reflect that. Thanks again!
– jrd1
yesterday





Easily. With a list comprehension:


a = [("roll", x) for x in a]



or with itertools stuff:


itertools


import itertools

a = list(zip(itertools.repeat('roll'), a)) # No need to wrap in list if you'll iterate the result and discard it



You can also use map function:


map


i = (1,2,3,4)
list(map(lambda x: ('roll',x), i))





Note: Any use of map that requires a lambda to work is more efficiently and more clearly expressed as a list comprehension or generator expression, since the listcomp/genexpr can inline the work done in the lambda, avoiding (relatively expensive) function call overhead for trivial work.
– ShadowRanger
yesterday




map


lambda


lambda



Or another alternative using list()


list(zip(["roll"]*4, a))






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS