Write a Python program to print the first and last element of the list

Python | Get first and last elements of a list

Sometimes, there might be a need to get the range between which a number lies in the list, for such applications we require to get the first and last element of the list. Let’s discuss certain ways to get the first and last element of the list.

Method #1 : Using list index
Using the list indices inside the master list can perform this particular task. This is most naive method to achieve this particular task one can think of.




# Python3 code to demonstrate
# to get first and last element of list
# using list indexing
# initializing list
test_list = [1, 5, 6, 7, 4]
# printing original list
print ("The original list is : " + str(test_list))
# using list indexing
# to get first and last element of list
res = [ test_list[0], test_list[-1] ]
# printing result
print ("The first and last element of list are : " + str(res))
Output: The original list is : [1, 5, 6, 7, 4] The first and last element of list are : [1, 4]


Method #2 : Using List slicing
One can also make use of list slicing technique to perform the particular task of getting first and last element. We can use step of whole list to skip to the last element after the first element.




# Python3 code to demonstrate
# to get first and last element of list
# using List slicing
# initializing list
test_list = [1, 5, 6, 7, 4]
# printing original list
print ("The original list is : " + str(test_list))
# using List slicing
# to get first and last element of list
res = test_list[::len(test_list)-1]
# printing result
print ("The first and last element of list are : " + str(res))
Output:

The original list is : [1, 5, 6, 7, 4] The first and last element of list are : [1, 4]


Method #3 : Using list comprehension
List comprehension can be employed to provide a shorthand to the loop technique to find first and last element of the list. Naive method of finding is converted to a single line using this method.




# Python3 code to demonstrate
# to get first and last element of list
# using list comprehension
# initializing list
test_list = [1, 5, 6, 7, 4]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension
# to get first and last element of list
res = [ test_list[i] for i in (0, -1) ]
# printing result
print ("The first and last element of list are : " + str(res))
Output: The original list is : [1, 5, 6, 7, 4] The first and last element of list are : [1, 4]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python Programs
Python list-programs
Read Full Article

Python program to interchange first and last elements in a list

Given a list, write a Python program to swap first and last element of the list.

Examples:

Input : [12, 35, 9, 56, 24] Output : [24, 35, 9, 56, 12] Input : [1, 2, 3] Output : [3, 2, 1]

Approach #1: Find the length of the list and simply swap the first element with (n-1)th element.

Python3




# Python3 program to swap first
# and last element of a list
# Swap function
def swapList(newList):
size = len(newList)
# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))

Output:

[24, 35, 9, 56, 12]

Approach #2: The last element of the list can be referred as list[-1]. Therefore, we can simply swap list[0] with list[-1].



Python3




# Python3 program to swap first
# and last element of a list
# Swap function
def swapList(newList):
newList[0], newList[-1] = newList[-1], newList[0]
return newList
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))

Output:

[24, 35, 9, 56, 12]

Approach #3: Swap the first and last element is using tuple variable. Store the first and last element as a pair in a tuple variable, say get, and unpack those elements with first and last element in that list. Now, the First and last values in that list are swapped.

Python3




# Python3 program to swap first
# and last element of a list
# Swap function
def swapList(list):
# Storing the first and last element
# as a pair in a tuple variable get
get = list[-1], list[0]
# unpacking those elements
list[0], list[-1] = get
return list
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))

Output:

[24, 35, 9, 56, 12]

Approach #4: Using * operand.
This operand proposes a change to iterable unpacking syntax, allowing to specify a “catch-all” name which will be assigned a list of all items not assigned to a “regular” name.

Python3




# Python3 program to illustrate
# the usage of * operarnd
list = [1, 2, 3, 4]
a, *b, c = list
print(a)
print(b)
print(c)

Output:

1 [2, 3] 4

Now let’s see the implementation of above approach:

Python3




# Python3 program to swap first
# and last element of a list
# Swap function
def swapList(list):
start, *middle, end = list
list = [end, *middle, start]
return list
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))

Output:

[24, 35, 9, 56, 12]

Approach #5: Swap the first and last elements is to use the inbuilt function list.pop(). Pop the first element and store it in a variable. Similarly, pop the last element and store it in another variable. Now insert the two popped element at each other’s original position.

Python3




# Python3 program to swap first
# and last element of a list
# Swap function
def swapList(list):
first = list.pop(0)
last = list.pop(-1)
list.insert(0, last)
list.append(first)
return list
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))

Output:

[24, 35, 9, 56, 12]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python Programs
Python list-programs
python-list
Practice Tags :
python-list
Read Full Article

Reading the First and Last Elements of a Python List

Elements in a list are numbered zero onwards. In this tutorial, we will learn different ways to access the first and the last elements from a list.

Let’s start by initializing a list.

1. Initialize a Python list

To initialize a list in Python use:

a = [6, 5, 9, 7]

This will initialize a new list ‘a‘ with the four elements we have mentioned.

2. Accessing list elements

You can access elements from the list by using the name of the list along with an index number. To print the first element use:

print(a[0])

To print the last element use :

print(a[-1])

Using -1 as the index gives us the last element from the list.

Python Code to Get First and Last Element of a List

The complete code is as follows :

a = [6, 5, 9, 7] print("first element is" ,a[0]) print("last element is", a[-1])

Output

Get first and last elements of a list in Python

PythonServer Side ProgrammingProgramming

There may be situation when you need to get the first and last element of the list. The tricky part here is you have to keep track of the length of the list while finding out these elements from the lists. Below are the approaches which we can use to achieve this. But of course all the approaches involve using the index of the elements in the list.

“python print first and last element of list” Code Answer


Python get first element from list
python by Hilarious Hoopoe on Sep 12 2020 Comment
2
Add a Grepper Answer

Python answers related to “python print first and last element of list”

  • python how to get the last element in a list
  • last element of list python
  • how to get the last value in a list python
  • how to find the last item of a list
  • how to print last element in a list python
  • get every item but the last item of python list
  • method get first last name python
  • how to get last element of list in python
  • python last element of list
  • python list last element
  • find last element in list python
  • python last item in list
  • find last index of element in list python
  • get the last element from the list
  • python get the last element from the list

Python queries related to “python print first and last element of list”

  • python get first element of list
  • python get first item in list
  • get first item in list python
  • python return first item in list
  • python get first 5 elements of list
  • get first element of array python
  • python first() last()
  • how to get the first element of a list in python
  • print the first element of a list in python
  • get first element in list python
  • how to get the first matching element of a list in python
  • get list of list where first element is
  • pick first value in an array python
  • ffirst element in list python
  • python get all first elements of list
  • how to assign first element of a sublist to a variable python
  • first item as a list is the same python
  • get first item list loop python
  • python get first element of set
  • take first element of array in python
  • python get first 3 elements in list
  • how to return the first element in an array in python
  • python check first element
  • get the first element of a list python
  • python variable print 1st item in list
  • printing the first object in a list
  • get first value in list
  • get first element array python
  • get first element list python
  • define first value item in list python
  • select first element of list python
  • python get the first element of a list
  • python first in list
  • get first item in array python
  • get the first value of a list in python
  • how to access first item in list python
  • python get first list item
  • take the first element of a list of lists
  • get first from list
  • return the first element of an array python
  • list python get first element
  • python find first item in list
  • python list read list from first item
  • find first element in list python
  • get first element of a list
  • get first value in a list python
  • how we can get first value from list in python new syntax
  • python find first element of a list
  • python how to get first element in list
  • python get the element of the first list
  • get first element function python
  • get the first 10 elemnts of a list python
  • how to get first element of a list of list python
  • how do i discover the first item in a list python
  • python array only getting first element
  • get first 100 of list
  • how we can get first value from list in python
  • ptyhon list take first
  • get the first elemr in of the list
  • python access first element in list
  • print first some element of list python
  • first item from list python
  • get first element of list of strings python
  • python print first element in list
  • python lose first elemen of list
  • relocate elements in a list to the first element python
  • python access first element in set
  • take first 5 elements of list python
  • grab the first element of a list in value python
  • find first python in list
  • what is the first element of a list
  • python select first element from list
  • make element first in the list python
  • get the first item in a list in python 3
  • get the first value in list
  • only returning first letter of list pythonm
  • python get the first list#
  • python3 get first 10 items from list
  • get first element from list
  • first list python
  • python list find first element
  • how to get first value in a list python
  • python list get first row
  • how to only move the first item of a list
  • how get first 3 of list
  • get the first 100 out of a list
  • how to get the first array in a list python
  • return first element in python list
  • python get first from all the lists
  • how to get the first element of python array
  • python get first item of array
  • python get the first item in a list
  • python list get first element object
  • how to get the first element of list in python
  • python how to print first element in list
  • get the first value of a list py
  • how to get first element from list python
  • first item on list of list
  • how to print first element in list
  • how to get first elements in an array in python
  • how to acces teh fiest item in a list from the the last index plus 1
  • take first item of list python
  • get first item of array python
  • get first item in a list python
  • how to get first element of an array python
  • python get first and last number from a list
  • python get first first item of list
  • get first index of list in python
  • take the first from each list python
  • get first item from list python
  • python get first element in array
  • retain first 3 elements of list python
  • how to get the first element in a list python
  • python print first thing in list
  • python get first value in list
  • get first object in array python
  • first list element python
  • get first and last element list python
  • python list get the first 10 element
  • first element of the list python
  • how to read first element of list inside list python
  • pthon firs item in array
  • print first list element python
  • function for giving the first element of list
  • python list print first element of list
  • get first item in python list
  • get first item of list
  • get first elment in list python
  • python sequence get first
  • python list get firstelement
  • get first element in sub list python
  • write a function that returns the first element of a list python
  • python3 get the first entry of a list
  • python list first
  • how to print the first item of a list of lists in python
  • python3 get first element of list
  • list.first in python
  • python get frist item from list
  • how to get the first item in a list python
  • python get first item in lsit
  • python3 get first item in array
  • python list first last element
  • how to get first utem in python
  • how to return the first item in a list python
  • selecting all the first elements from a list of list
  • list get first python
  • get first element of list python
  • first element of list python
  • get first element python
  • select first elements in list python
  • how to get the first item of a list in python
  • how to print first element of list in python
  • how to print the first thing in a list python
  • python get first item from list
  • python how to look at an the first item in the list
  • first first value of an array in python
  • print first last item list python function
  • python get first elemtn in list
  • python get first element
  • get first index of list python
  • get from python list first certain elements
  • how to get first and last element of list in python
  • select first item in list python
  • get first list from list of lists python
  • access first element of list python
  • python array get first element
  • how to get first element of list in python
  • print first elemen found
  • print first element array python
  • list get first element python
  • python get first in list
  • printing first some elements of list
  • python sequence get first element
  • find the first two elements of the list
  • check first element of list python
  • python get first element of array
  • how to return the first item of a list python
  • get first item of list python
  • python list print first element
  • how to print the first element of a list in python
  • get first element from output in python
  • python print list first
  • get first elements of list python
  • get first of list python
  • get first item of list of lists python
  • get first items of list
  • python list of list access first element
  • accessing first element in python list
  • list of list first entry python
  • get only first value from list python
  • get only first from list
  • python get first item from array
  • python extract first element from list
  • how to get the first element in list
  • python array extract first element
  • get the first item in a list python
  • get first from list of lists
  • get list without first element python
  • python get first element of list in list
  • find first value in list python
  • python list find first
  • python get the first element of an array
  • how to get 1st element of list in python
  • python list get first element
  • how to access first object in list python
  • how to find the first of a item in a list in python
  • get all first item in list python
  • python get first of list
  • select first element in array python
  • python3 how to extract first item in a set
  • get first 10 items in list python
  • how to access first items in python list
  • how to get first item of list
  • python list extract first element
  • extract first element grom a list in purrr
  • send first element of list to end python
  • how to read first element of list in python
  • first element of list in python
  • get first 10 list in python
  • python list get first element or none
  • python list get first 10 elements in list
  • get first value of list
  • python select from list of list get 1st element from each
  • first item in a list python
  • how to print only first item in list
  • how to get first element of each array in list python
  • first item in items python
  • create python function to get first number of list
  • python list first item
  • command to extract first elemnt in list python
  • hopython how to select first item in a list
  • python take first element
  • take out first element from list
  • get first list index
  • access list 1st item in array python
  • get first elelment from list
  • how to call first element in list python
  • retrieve first value from list python
  • how to print first 5 items from the list text analysis python
  • get first and last element of a list
  • python select first item in a list
  • how get firet of the list python
  • take first element of a list python
  • reference first element of a list in python
  • get first values of list python
  • get first element of a list python
  • grab first 6000 items list python
  • first of an element in a list pyton
  • print first last item list python
  • python check first element of list
  • python get first item in array
  • get first item of list in python
  • extract any one element from list python
  • get the first item of a list python
  • how to get the first value of a list in python
  • python function print frst item in a set of lists
  • how to get list of lists first value
  • python get fisrt item from list
  • python print out first item in list
  • return list from last to first
  • first element python
  • return the first one in python
  • how to get first item in list python
  • extract the elements from the list python
  • python first elemnt of list
  • print first and last 10 list element spython
  • get the first value out of a list python
  • get first entry of list python
  • access every first and second items in list python
  • get the first and last value of a list python
  • python get first element of list when list end riched
  • how to access the first item out of a list in python
  • get all the first elments in list of list python
  • find first item of list
  • python get first 5 items in list
  • liste first elements from a list pyhton
  • print first items in the list in python
  • get 0th item of list python
  • python first element in a list
  • get first element pyspark
  • get the frist enad las value in an list
  • accessing the first element of a list of lists
  • how to get the first number in a list
  • python get first number of elements from list
  • python best way get first item in list
  • first and last value show in for with flask
  • how to print list in first last pattern
  • print only the first item in a list python
  • python get first to
  • python first element list
  • how to access the first item of every list in the list in python
  • get first item array python
  • python first element in list
  • python first element of list
  • python list first element
  • get first value of list in python
  • print function first last item list python
  • how to get first element of array in python
  • first and last two elemts of a list python
  • get first value of list python
  • get value of first element in list python
  • how to know with item comes first in python list
  • output first element from array python
  • python list 1 list get first element
  • get the first item of python list
  • get first index of value list python
  • how to print first and last item in list python
  • python get first element from list
  • how to have the first thing in a list number 1 python
  • how access first and second item in list python
  • get first value from array python
  • first item in list python
  • first value in list python
  • first item of list python
  • first element list python
  • get first item of an array python
  • how to check if the element is the 1st element iin list python
  • python first list
  • get first element of dictionary python
  • python print first and last element of list
  • print first element of list python
  • get first item from a list in python
  • python get first
  • print first elements form list python
  • python print first item in list
  • first item in list
  • extract first element of list and put into array python
  • get first row of list python
  • python get dict first from list
  • python select first value from list
  • python list select first value
  • python how to extract the first item from a list
  • get first items of list of lists python
  • from first element of array python
  • how to get a list without the first element python
  • python get returning first element of list
  • how to take out the first value of a list
  • access the first list python
  • how to get the first item of an list
  • how to access the first element in a list in python
  • how to get first value of a list in python
  • python get first 100 items in list
  • python get first elements of list
  • python get first 3 items of list
  • get the first element of an array python
  • python get first 20 element of list
  • how to get first 5 element from list python
  • how to get first index of list python\
  • list get first element
  • python safe get first element of list
  • python get x first from list
  • how to get the first part of a list in python
  • how to get elements after first elements in the list
  • how to get first argument in list python
  • list extract first value python
  • get first item in a set python
  • python choose every first element in list
  • only keep the first index in a list python
  • get first value of array python
  • dict with lists gives only first element of list
  • get first element from set python
  • another method to get first element of list in python
  • python get list without first element
  • get first item in set python
  • python read first item from list
  • get the first item in list from left
  • get elements from list after the first
  • print first item in array python
  • python first of list
  • find first instance in list python
  • how to find first element of list in python
  • take first 100 from list
  • how to get first element of a list in python
  • how do you refer to the first value in your list in python
  • python get first element of list to string
  • python list except first element
  • python set get first
  • how to select first objects in list in python
  • extract the first string in list python
  • python list access first element in each element
  • python return first n elements of list
  • python find first in list
  • python fisrt item
  • python how to print only the first item in a list
  • hpython how to print first and last item of a list
  • how to get first eleement of a list in python
  • how to choose the first item in a list python
  • how to get first index of a list
  • how to make the first index the last index in a list python
  • python found first elem of lsit
  • grab first element of list python
  • first item on list
  • python first item in list that
  • python only print first item in for
  • how to print first items in a list python
  • how to select the first item in a list python
  • python list get first and last element
  • select first element in a list
  • python list first and last element
  • take first and last of a list pythin
  • python first item of list
  • python list get the first element
  • for i in list python index 1st element
  • get first value from list python
  • python get first list entry
  • python how to take only first number of items in a list
  • python get first method
  • python get 1st element in list
  • for print first item last
  • how to make a list of first index of a list of lists
  • how to print the first index of a list
  • how to get the first item of a list python
  • python3 get first item from list
  • get first value of a python lit
  • select first elemet in python
  • python first item in list
  • python print first x element in list
  • python string list get first element
  • get first element of list of list python
  • the print first element of the list
  • get a list with the first element of a list
  • get first element in a list python
  • take first words of list values python
  • python pick first item in list
  • get the first element of dictionary python
  • python get all first elements of lits
  • first elt list python
  • python get first element in list
  • python get 1st item in list
  • python keep only first list element
  • get first and last element of list python
  • how to reference first item list python
  • first element in a list python
  • get first item of a list python
  • first element in list comprenhension
  • python get first element of every list in list of lists
  • how to add first element from list python
  • python set get first element

Python Program to Interchange First and Last Elements in list

In this tutorial, you will learn how to interchange the first and the last elements in a list in Python. Lists in Python are a group of ordered values that are closed within a square[] bracket. For a given list, we have to write a Python program that will swap the first and the last elements of a list. Swapping means exchanging the values of the two numbers. Suppose you have two variables a and b. The value of a is 40 and the value of b is 30. After swapping the value of a will become 30 and the value of b will become 40.

For a list a[ ]= [1, 2, 3, 4, 5], swap elements at position 1 and position 5

To get the final list as a[]=[5,2,3,4,1]

Get the last element of a list using indexing in Python

Indexing in python is a way to access elements from a list. In python, we can use positive indices as well as negative indices. Positive indices start with zero which corresponds to the first element of the list and the last element of the list is identified by the index “listLen-1” where “listLen” is the length of the list.

Alternatively, negative indices start from -1 which corresponds to the last element of the list. It goes till “-listLen” where listLen is the length of the list. The index “-listLen” corresponds to the first element in the list.

To get the last element of a list, we can first find the length of the list using the len() function. Then we can access the last element of the list at the index “listLen-1” as follows.

myList = [1, 2, 3, 4, 5, 6, 7] print("Given List is:", myList) listLen = len(myList) lastElement = myList[listLen - 1] print("Last element of the list is:", lastElement)

Output:

Given List is: [1, 2, 3, 4, 5, 6, 7] Last element of the list is: 7

Alternatively, we can use negative indexing to access the last element of the list. The last element of the list is at index -1 which can be accessed as follows.

myList = [1, 2, 3, 4, 5, 6, 7] print("Given List is:", myList) lastElement = myList[- 1] print("Last element of the list is:", lastElement)

Output:

Given List is: [1, 2, 3, 4, 5, 6, 7] Last element of the list is: 7

We can see that while using negative indexing, we don’t have to calculate the length of the list.

What is a List in Python?

The list is one of the most commonly used data types in Python. A list is a collection of elements that can be of any data type. A single list can contain a combination of numbers, strings, nested lists, etc.

How to Get the Last Element of a List in Python

Method 1 – By Iterating all the elements in a list

The most common and straightforward way to get last element in list is through iterating the entire element till it reaches the last element, as shown below.

# Python code to access the last element # in a list using for loop # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) # using loop method to print last element for i in range(0, len(number_list)): if i == (len(number_list)-1): print ("The last element of list is : "+ str(number_list[i])) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list is : 6

Method 2 – Using the reverse() method

The reverse()method in Python is used to reverse the elements of a list. The reverse() method does not take any arguments and does not return any values instead, it reverses the existing list.

# Python code to access the last element # in a list using reverse() method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) # using reverse method to print last element number_list.reverse() print("The last element of list using reverse method are : " + str(number_list[0])) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

Method 3 – Using pop() method

The pop() method is used to access the last element of the list and returns the removed item. Thepop() method accepts an integer as the argument, which is basically the index of the item which needs to be removed from the list.

Example – list.pop(0) will remove and return the first element in the list.

Note – Calling the pop()method will remove the last item from the list itself. Hence if you are re-using the list, this approach is not recommended as the element is removed.

# Python code to access the last element # in a list using pop() method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) # using pop() method to print last element print("The last element of list using reverse method are : " + str(number_list.pop())) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

Method 4 – Using Negative Indexing [] Operator

The negative index is the way of indexing the element from the end of the list with an index starting from -1, i.e., -1 gives the last element, -2 gives the last 2nd element, and so on.

The major use of negative indexing can be used to reverse a list without using any built-in function.

You can also find the last element in the list using length-1. In order to access the last element, we need to know the length of the list.

# Python code to access the last element # in a list using negative indexing # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) # using length-1 to print last element print("The last element of list using length-1 method are : " + str(number_list[len(number_list) -1])) # using [] operator to print last element print("The last element of list using reverse method are : " + str(number_list[-1])) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using length-1 method are : 6 The last element of list using reverse method are : 6

Method 5 – Using itemgetter()

The operator module in Python has vast features to perform all mathematical, logical, comparison operations.

Theitemgetter()method is one of the methods in the operator module, and it accepts one or more integer arguments and returns the callable object.

import operator # Python code to access the last element # in a list using itemgetter() method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ("List of elements are : " + str(number_list)) getLastElement = operator.itemgetter(-1) # using [] operator to print last element print("The last element of list using reverse method are : " + str(getLastElement(number_list))) # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

Python program to interchange first and last element in a list

Here, we will write a Python program in which we will interchange the first and list element of the list.
Submitted by Shivang Yadav, on April 06, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered sets of values enclosed in square brackets [].

Python program to interchange first and last element in last

In this program, we will swap the first and last elements of the list.

Example:

Input: [4, 1, 7, 3, 90, 23, 56] Output: [56, 1, 7, 3, 90, 23, 4]

Solution Approach:

We will simply need to swap elements at the first index with the element at the last index in the list.

Python provides multiple ways to perform the task. Let's see them,

Method 1:

In this method, we will find the length of the list. And then swap the element at index 0 and element at index (length - 1).

Algorithm:

  • Find the length of the list
  • Swap values at list[0] and list[len - 1]
    • temp = list[0]
    • list[0] = list[length - 1]
    • list[length - 1] = temp
  • Return the list

Program to interchange first and last element in the list

# Python program to interchange the # first and last element of a list # Creating a list myList = [1, 7, 3, 90, 23, 4] print("Initial List : ", myList) # finding the length of list length = len(myList) # Swapping first and last element temp = myList[0] myList[0] = myList[length - 1] myList[length - 1] = temp print("List after Swapping : ", myList)

Output:

Initial List : [1, 7, 3, 90, 23, 4] List after Swapping : [4, 7, 3, 90, 23, 1]

Method 2:

Another method to interchange values is using Python's shorthand technique to find the last element. And then swapping them.

The last element can be found using list[-1].

Algorithm:

  • swap -> list[0] and list[-1].
    • temp = list[-1]
    • list[-1] = list[-0]
    • list[0] = temp
  • Print list

Program to interchange first and last element in the list

# Python program to interchange the # first and last element of a list # Creating a list myList = [1, 7, 3, 90, 23, 4] print("Initial List : ", myList) # Swapping first and last element temp = myList[-1] myList[-1] = myList[0] myList[0] = temp print("List after Swapping : ", myList)

Output:

Initial List : [1, 7, 3, 90, 23, 4] List after Swapping : [4, 7, 3, 90, 23, 1]

Method 3:

In this method, we will use the comma assignment method from python. Here, we will store the first and last element tuple to the last and first element tuple.

Syntax:

list[0], list[-1] = list[-1], list[0]

Program to interchange first and last element in a list

# Python program to interchange the # first and last element of a list # Creating a list myList = [1, 7, 3, 90, 23, 4] print("Initial List : ", myList) # Swapping first and last element myList[0], myList[-1] = myList[-1], myList[0] print("List after Swapping : ", myList)

Output:

Initial List : [1, 7, 3, 90, 23, 4] List after Swapping : [4, 7, 3, 90, 23, 1]

Method 4:

One more method, can be deleting the elements from the list and then inserting them back in the desired position.

Here, we will delete (pop) the first and the last elements of the list and insert them back as the first element at the last position and last element at the first position.

Algorithm:

  • Swap values
    • firstVal = list.pop(0)
    • lastVal = list.pop(-1)
    • list.insert(0, lastVal)
    • list.append(firstVal)
  • Print list

Program to interchange first and last element in a list

# Python program to interchange the # first and last element of a list # Creating a list myList = [1, 7, 3, 90, 23, 4] print("Initial List : ", myList) # Swapping first and last element firstVal = myList.pop(0) lastVal = myList.pop(-1) myList.insert(0, lastVal) myList.append(firstVal) print("List after Swapping : ", myList)

Output:

Initial List : [1, 7, 3, 90, 23, 4] List after Swapping : [4, 7, 3, 90, 23, 1]

Python List Programs »

Python program to swap any two elements in the list
Python program to find the cumulative sum of elements of a list

ADVERTISEMENT


Preparation


Aptitude Questions MCQs Find Output Programs

What's New

  • MongoDB MCQs
  • Java MCQs
  • C# MCQs
  • Scala MCQs
  • Blockchain MCQs
  • AutoCAD MCQs
  • PHP MCQs
  • JavaScript MCQs
  • jQuery MCQs
  • ReactJS MCQs
  • AngularJS MCQs
  • JSON MCQs
  • Ajax MCQs
  • SASS MCQs
  • HTML MCQs
  • Advanced CSS MCQs
  • CSS MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • MS Word MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • Software Engineering MCQs
  • MIS MCQs
  • Generally Accepted Accounting Principles MCQs
  • Bills of Exchange MCQs
  • Business Environment MCQs
  • Sustainable Development MCQs
  • Marginal Costing and Absorption Costing MCQs
  • Globalisation MCQs
  • Indian Economy MCQs
  • Retained Earnings MCQs
  • Depreciation MCQs
  • Partnership MCQs
  • Sole Proprietorship MCQs
  • Goods and Services Tax (GST) MCQs
  • Cooperative Society MCQs
  • Capital Market MCQs
  • Business Studies MCQs
  • Basic Accounting MCQs
  • MIS Executive Interview Questions
  • Go Language Interview Questions
ADVERTISEMENT

Top Interview Coding Problems/Challenges!

  • Run-length encoding (find/print frequency of letters in a string)
  • Sort an array of 0's, 1's and 2's in linear time complexity
  • Checking Anagrams (check whether two string is anagrams or not)
  • Relative sorting algorithm
  • Finding subarray with given sum
  • Find the level in a binary tree with given sum K
  • Check whether a Binary Tree is BST (Binary Search Tree) or not
  • 1[0]1 Pattern Count
  • Capitalize first and last letter of each word in a line
  • Print vertical sum of a binary tree
  • Print Boundary Sum of a Binary Tree
  • Reverse a single linked list
  • Greedy Strategy to solve major algorithm problems
  • Job sequencing problem
  • Root to leaf Path Sum
  • Exit Point in a Matrix
  • Find length of loop in a linked list
  • Toppers of Class
  • Print All Nodes that don't have Sibling
  • Transform to Sum Tree
  • Shortest Source to Destination Path

Comments and Discussions!



Please enable JavaScript to view the comments powered by Disqus.
ADVERTISEMENT

Video liên quan

Postingan terbaru

LIHAT SEMUA