“Échangez 2 éléments d'une liste dans Python” Réponses codées

Échangez les éléments de liste dans Python

lst = ["a","b","c","d","e","f","g","h","i","j"]
n = len(lst)
for i in range(0,n-1,2):
    lst[i],lst[i+1] = lst[i+1],lst[i]
print(lst)
print(n)
King Generous

Échangez 2 éléments d'une liste dans Python

in python below is how you swap 2 elements of list
            x[i+1],x[i]=x[i],x[i+1]
Don't use function swap(user defined or pre-defined)
ap_Cooperative_dev

Échangez deux listes sans utiliser la troisième variable Python

list1=["Hi how are you"]
list2=["Iam fine"]
list1,list2=list2,list1
Fancy Fish

Comment échanger des éléments dans une liste de python détaillé

How to swap elements in a list in Python
1 Swap by index
2 Swap by value

Swapping two elements changes the value at each index. 
For example, swapping the first and last elements in ["a", "b", "c"] results in ["c", "b", "a"].

SWAP ELEMENTS BY INDEX IN A LIST
Use list[index] to access the element at a certain index of a list.
Use multiple assignment in the format val_1, val_2 = val_2, val_1 to swap the value at each index in the list.

a_list = ["a", "b", "c"]
a_list[0], a_list[2] = a_list[2], a_list[0]
swap first and third element

print(a_list)
OUTPUT
['c', 'b', 'a']
SWAP ELEMENTS BY VALUE IN A LIST
Use list.index(value) with each element as value to get their indices. 
Use multiple assignment to swap the value at each index in the list.

a_list = ["a", "b", "c"]

index1 = a_list.index("a")
index2 = a_list.index("c")
a_list[index1], a_list[index2] = a_list[index2], a_list[index1]

print(a_list)
OUTPUT
['c', 'b', 'a']
ap_Cooperative_dev

Réponses similaires à “Échangez 2 éléments d'une liste dans Python”

Questions similaires à “Échangez 2 éléments d'une liste dans Python”

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code