Coding is fun, and coding in Python is even more fun because there are many different ways to accomplish the same functionalities. However, most of the time, there are preferred implementations, which some people refer to as Pythonic. One common characteristic of these Pythonic implementations is the neatness and conciseness of the code.

Programming in Python or any coding language is not rocket science, and it’s mostly about crafting skills. If you intentionally try Pythonic coding, these techniques will soon become part of your toolkit, and you’ll find it more and more natural to use them in your project. So let’s explore some of these simple tricks, which I hope you’ll find helpful.

1. Negative Indexing

People like to work with sequences because we know the order of the elements, and we can operate these elements order-wise. In Python, strings, tuples, and lists are the most common sequence data types. We can access individual items using indexing. Like other mainstream programming languages, Python supports 0-based indexing, where we access the first element using zero within a pair of square brackets. Besides, we can also use slice objects to retrieve particular elements of the sequence, as shown in the code examples below.

>>> # Positive Indexing
... numbers = [1, 2, 3, 4, 5, 6, 7, 8]
... print("First Number:", numbers[0])
... print("First Four Numbers:", numbers[:4])
... print("Odd Numbers:", numbers[::2])
... 
First Number: 1
First Four Numbers: [1, 2, 3, 4]
Odd Numbers: [1, 3, 5, 7]

However, Python takes a step further by supporting negative indexing. Specifically, we can use -1 to refer to the last element in the sequence and count the items backward. For example, the last but one element has an index of -2 and so on. Importantly, the negative indexing can also work with the positive index in the slice object.

>>> # Negative Indexing
... data_shape = (100, 50, 4)
... names = ["John", "Aaron", "Mike", "Danny"]
... hello = "Hello World!"
... 
... print(data_shape[-1])
... print(names[-3:-1])
... print(hello[1:-1:2])
... 
4
['Aaron', 'Mike']
el ol

#python

10 Tricks for Write Better Python Code
5.75 GEEK