Python Forum

Full Version: modifying a list in an expression
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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)])
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.