Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

swap list items in 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)
Comment

list element swapping python

m=eval(input("enter number"))
for i in range(0,len(m),2):
    m[i],m[i+1]= m[i+1],m[i]
print("swapped list",m)
#output
enter number[1,2]
swapped list [2, 1]
Comment

Swap 2 items of a list in 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)
Comment

How to swap elements in a list in Python detailed

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']
Comment

how to swap element in python list

.*    *.
*.    .*
Comment

PREVIOUS NEXT
Code Example
Python :: how to create list in python 
Python :: return more than one value python 
Python :: find position of key in dictionary python 
Python :: python string after character 
Python :: comment all selected lines in python 
Python :: .save() in django 
Python :: matrix multiplication python without numpy 
Python :: deque python 
Python :: master python 
Python :: search method in python 
Python :: github downloader 
Python :: json diff python 
Python :: python code to add element in list 
Python :: dataframe names pandas 
Python :: syntax of ternary operator 
Python :: how to make a letter capital in python 
Python :: sys python 
Python :: infinity range or infinity looping 
Python :: string contains element of list python 
Python :: Class 10: Conditional Statements in Python [IF, ELIF, ELSE] 
Python :: python string: built-in function len() 
Python :: check if string has square brackets python 
Python :: print A to Z in python uppercase 
Python :: iif python 
Python :: Define the learnable resizer utilities 
Python :: numpy array filter and count 
Python :: Filter xarray (dataarray) 
Python :: calculate time between datetime pyspark 
Python :: how to import alpha vantage using api key 
Python :: python 2.0 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =