Python Forum
modifying a list in an expression - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: modifying a list in an expression (/thread-16096.html)



modifying a list in an expression - Skaperen - Feb-14-2019

i have some incoming data. each unit of data can be converted to a list. that list can be converted back to that data. the conversions are expressions. i can nest these two expression to convert the data to a list and then back. i have a modification to the data that is defined in terms of it being in the list form. the modification is copying element index B to element index A of the list like. i can do this in 3 lines:

    temp = convert_data_to_list(data)
    temp[A] = temp[B]
    data = convert_list_to_data(temp)
is there an easy way to use slicing (or something else) to make this all be a single expression?


RE: modifying a list in an expression - perfringo - Feb-14-2019

Something like this (as you can see it's readability is not great)?

convert_list_to_data([convert_data_to_list(data)[B] if convert_data_to_list(data).index(x) == A else x for x in convert_data_to_list(data)])



RE: modifying a list in an expression - Skaperen - Feb-15-2019

that's also going to be slow. the code i gave is actually going to be in a loop affecting many units of data (each unit can be converted to a list). most units are strings and conversion to a list was a workaround because they are immutable. i guess squeezing this to a big expression in one line is just not going to happen.

and, yeah, it is harder to read. so i guess it's back to separate steps.