Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Python Element Swap Coding

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Python Element Swap Coding. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Teamware Solutions processes ordered items in Python lists and occasionally needs to exchange two positions without creating a second list. Implement a function that swaps the elements at two provided indices in place and returns the modified list.

Formal Specification

Implement swap_elements(arr, index1, index2).

  • Input: arr, a list of integers, and two valid zero-based integer indices, index1 and index2.
  • Output: The same list object after the values at index1 and index2 have been exchanged.
  • The function must not change the list length or the values at any other positions.
  • If both indices are equal, the list remains unchanged.

Constraints

  • 1 <= len(arr) <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • 0 <= index1, index2 < len(arr)
  • The input indices are valid
  • The list must be modified in place

Function Signature

def swap_elements(arr, index1, index2):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output