Let's consider very simple probem, if I have list:
x = ["a", "b", "c", "d", "e"]
and I want to transform it by adding "_x" at the end of string. In other words I desirable output is:
x = ["a_x", "b_x", "c_x", "d_x", "e_x"]
Of course I can just loop over strings:
for i in range(len(x)):
x[i] = x[i] "_x"
But I'm searching of more efficient solution. Could you please give me a hand with doing so?
CodePudding user response:
If you want to modify the list in-place, the only "better" solution is a listcomp that is assigned back to the complete slice of the original list:
x[:] = [item '_x' for item in x]
which, unlike:
x = [item '_x' for item in x]
will modify any aliases that refer to the same original list (e.g. if a caller passes such a list to a function, the former will modify the caller's list as well, the latter will not).
CodePudding user response:
You can use list comprehensions :
print([item '_x' for item in x])
print([f"{item}_x" for item in x])
It's a little bit faster than loops, but definitely more readable.
list comprehensions create new lists, they don't modify the existing list. You can then rebind the result to x or do a slice assignment like x[:] = ...
CodePudding user response:
You can also use map():
[In] list(map(lambda x: x '_x', your_list))
[Out] ['a_x', 'b_x', 'c_x', 'd_x', 'e_x']
CodePudding user response:
For in-place modification of the list you can combine map with subscript assignment:
x = ["a", "b", "c", "d", "e"]
x[:] = map("{}_x".format,x)
print(x)
['a_x', 'b_x', 'c_x', 'd_x', 'e_x']
