python - function that changes the position of 2 elements in a list -
I have to type a function that will work if I will write it:
s = [ "John", "Bartha", "Jenna", "Daniel", "Emma"] change (S, 2,4) print (s) ["John", "Bertha", "Emma", "Daniel" "Jenna "]
I basically have to define the function that changes the status of 2 elements in a list, where a, b
are indexed by them.
I have tried to do this, but I can not find any good solution:
def change (s, a, b): a, b = S Index (A), S. Indicate (B) S [B], S [A] = S [A], S [B]
It does not work clearly, I do not know that I How can I change the position of elements where a, b
are indexed, I know how to switch 2 items, but there is no clue how to do this with functions. Grow?
one
and b
Em> indexes are the ones you want to switch to. If you already know where they are, you can remove the call at list.index
:
& gt; & Gt; & Gt; S = ["John", "Bertha", "Jenna", "Daniel", "Emma"]> gt; & Gt; & Gt; Def changes (S, A, B): ... S [B], S [A] = S [A], S [B] ...> gt; & Gt; & Gt; Change (S, 2, 4) & gt; & Gt; & Gt; S ['John', 'Bertha', 'Emma', 'Daniel', 'Jenna'] & gt; & Gt; & Gt;
Comments
Post a Comment