Knowee
Questions
Features
Study Tools

Complete this code to swap the first and last element of the given array. Do nothing if the array is empty.

Question

Complete this code to swap the first and last element of the given array. Do nothing if the array is empty.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python solution for your problem:

def swap_elements(arr):
    if len(arr) == 0:
        return arr
    else:
        arr[0], arr[-1] = arr[-1], arr[0]
        return arr

This function swap_elements takes an array arr as input. If the array is empty (i.e., its length is 0), it returns the array as is. Otherwise, it swaps the first and last elements of the array using Python's multiple assignment feature, and then returns the modified array.

This problem has been solved

Similar Questions

Given an array arr of n positive integers. The task is to swap every ith element of the array with (i+2)th element.

Given an array of N integers containing only 0 or 1. You can do the following operations on the array:swap elements at two indiceschoose one index and change its value from 0 to 1 or vice-versa.You have to do the minimum number of the above operations such that the final array is non-decreasing.Note Consider 1 based Array-indexing

Given an array of integers, you have to write a program to swap the elements in the first and last locations, the second and last before location, and so on.ExamplesInput: {12, 23, 34, 48, 57}Output: {57, 48, 34, 23, 12} Input: {14, 15, 16, 23, 45, 87, 19, 96}Output: {96, 19, 87, 45, 23, 16, 15, 14} Note: This question helps in solving the technical coding tests of DXC and Capgemini.Input format :The first line of input consists of an integer N, the number of array elements.The second line consists of N space-separated array elements.Output format :The output prints the array of elements after swapping the elements.Refer to the sample output for formatting specifications.Code constraints :1 ≤ N ≤ 301 ≤ array elements ≤ 103Sample test cases :Input 1 :512 23 34 48 57Output 1 :57

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

Note: Keep the first position of the array unaltered.

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.