In [13]:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:103% !important;margin-left: -2%; }</style>"))
interchange first and last elements in a list¶
In [2]:
l1=[1,2,3,4,5]
l1
Out[2]:
[1, 2, 3, 4, 5]
In [6]:
# Getting the first element
temp_first=l1[0]
temp_first
Out[6]:
1
In [7]:
# Getting the last element
temp_last=l1[len(l1)-1]
temp_last
Out[7]:
5
In [8]:
# Swapping values
l1[0]=temp_last
l1[len(l1)-1]=temp_first
In [9]:
# Printing the list
l1
Out[9]:
[5, 2, 3, 4, 1]
Creating a function to perform this swapping¶
In [10]:
def swapping_element(L1):
l1=[]
l1=L1
temp_first=l1[0]
temp_last=l1[len(l1)-1]
# Swapping values
l1[0]=temp_last
l1[len(l1)-1]=temp_first
return(l1)
In [11]:
swapping_element([1,2,3])
Out[11]:
[3, 2, 1]
In [12]:
swapping_element([12,17,20])
Out[12]:
[20, 17, 12]
No comments:
Post a Comment