# Neat tricks with Python arrays
Published on 24 October 2019

As a Java developer Python amazes me how things can be done stupid simple. 

Try to reverse a string in java:

    public static void main(String[] args) {
        String mytext = "abcdefg";
        StringBuilder result = new StringBuilder();
        for (int i = mytext.length(); i > 0; i--) {
            result.append(mytext.charAt(i-1));
        }
        System.out.println(result);
    }

 

Do it in Python:

mytext = "abcdefg"[::-1]
print(mytext)

 

The array indexing and slicing explained:

"abcdefg"[<start>:<stop>:<steps>]

 

  Value Explaination
"abcdefg"[5] "f" Get the element on the 5th index number
"abcdefg"[2:] "cdefg" Slice the array from index 2 to the end
"abcdefg"[:2] "ab" Slice the array to index 2(exclusive)
"abcdefg"[1:4] "bcd" Get all elements starting from index 1 to index 4(exclusive)
"abcdefg"[2:7:2] "ceg" Get all elements starting from index 1 to index 7(exclusive), with steps of 2
"abcdefg"[::2] "aceg" From the beginning to the end, take steps of 2
"abcdefg"[::-1] "gfedcba" Take steps of -1 which actually iterates in reverse order.