How To Left Shift Array Elements In Python

In this tutorial, we will learn how to left-shift array elements in Python. Left shifting refers to shifting array elements one position to the left.

This means that the first element becomes the last element, and all other elements are moved to the left. This is a common operation in computer programming, and Python provides an efficient way to perform it.

Step 1: Create an array

First, let’s create a sample array using the Python list data structure. We will use this array in our next steps. You can create a list by enclosing elements in square brackets:

Step 2: Define a function to shift the array elements

Now, let’s create a function named left_shift_array that takes an array and a number n as inputs, and returns a new array that has its elements left shifted by n positions:

The function uses slicing to shift the elements. It first takes the sublist from the n-th element to the last element (arr[n:]) and then concatenates it with the sublist from the first element to the (n-1)-th element (arr[:n]).

Step 3: Test the function on the sample array

Now that we have our function defined, let’s test it on our sample array. We will shift the array by 2 positions to the left:

This should output the following:

[3, 4, 5, 1, 2]

The original array [1, 2, 3, 4, 5] has been left shifted by 2 positions, resulting in the new array [3, 4, 5, 1, 2].

Step 4: Test the function for different values of n

We can test our function with different values of n to see whether it works as expected:

This should output the following:

[1, 2, 3, 4, 5]
[2, 3, 4, 5, 1]
[1, 2, 3, 4, 5]

As we can see, our function works correctly for different values of n.

Full Code:

Here is the complete code for this tutorial:

Conclusion

In this tutorial, we learned how to create a function to left shift array elements in Python. This function can be useful in various programming situations where element shifting is required. Remember that the key to implementing this operation is to use Python’s efficient slicing capabilities to create sublists and concatenate them in the desired order.