Chapter 18: Swapping Values in a Python Array

preview_player
Показать описание
Describes the process to swap two values in a Python array.
Рекомендации по теме
Комментарии
Автор

Or simply list[0], list[2] = list[2], list[0] for shorter code..

YoungVinny
Автор

Good question. Two reasons I didn't include that:
1.) This is language specific. Teaching new programming students this technique will not help them in Java, C, C#, etc.
2.) I think more programmers will understand the three line swap code faster than that 1-line version. One could easily disagree with this, depends on what group of programmers you work with. Python veterans would obviously not have a problem with the one-liner.

professorcraven
Автор

for those who need to swap regularely, just make a function for it:

def swap(List, Swap_this, With_that):

temp = List[Swap_this]

List[Swap_this] = List[With_that]

List[With_that] = temp

print(List)

swap(list, 2, 0)
make the program do the work for you :)

Reneeke
Автор

What if I want a specific permutation?

xanthopurpurin
Автор

Sure, it makes sense. I didn't realize this wasn't a Python specific course. As a general, language-agnostic course, I agree.

thedweebo
Автор

You shouldn't use built-in names for variables

xanthopurpurin
Автор

Hi, What is the name of software that you draw the screen by red pencil?

SalihBALTALI
Автор

I need to get the max value of the list then swap that with the last index. So index[-1] would be Max’s index and max’s index would be index[-1] spot. How can I do this? Is it simple a, b = b, a ??

tannerbarcelos
Автор

Why not just use simultaneous assignment? Let's say you want to swap the 3rd element for the 5th in mylist: you can just type:
mylist[2], mylist[4] = mylist[4], mylist[2]
One line and done. The technique you present is fine, but can be simplified.

thedweebo