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:

1 |
arr = [1, 2, 3, 4, 5] |

### 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:

1 2 |
def left_shift_array(arr, n): return arr[n:] + arr[:n] |

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:

1 2 |
shifted_arr = left_shift_array(arr, 2) print(shifted_arr) |

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:

1 2 3 |
print(left_shift_array(arr, 0)) # No shifting print(left_shift_array(arr, 1)) # Shift by 1 position to the left print(left_shift_array(arr, 5)) # Shift by the array's length |

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:

1 2 3 4 5 6 7 8 9 10 |
def left_shift_array(arr, n): return arr[n:] + arr[:n] arr = [1, 2, 3, 4, 5] shifted_arr = left_shift_array(arr, 2) print(shifted_arr) print(left_shift_array(arr, 0)) print(left_shift_array(arr, 1)) print(left_shift_array(arr, 5)) |

## 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.