5 tips to make your Python code more pythonic

When we are programming in a certain language, it is always better to follow its community conventions and to use what the language offers you. Python is intended to have a clean and concise syntax, so we should take advantage of this. If you still haven't, type "import this" in the Python interpreter and read the "Zen of Python". Those are the Python Principles.

There are some common things I noticed when reading code from programmers comming from other languages. Not that they are mistakes, but they have a better way to be written:

1. Simple loops through object arrays

Don't:

i = 0
while i < n:
   print(arr[i])
   i+=1

Do use the for loop:

for element in arr:
   print(element)

2. loops when you need the index

Don't:

i = 0
for element in arr:
   print(i, element)
   i+=1

Do use enumerate to give you the index, since it is a more concise syntax:

 for index, value in enumerate([7,8,9]):
   print(index, value)

3. Verify if an array contains a certain value

Don't:

found = False
for value in arr:
  if value  == searched_value:
     found = True
     break

Do use the keyword in:

found = value in arr

4. Opening a file

Don't:

f = open('file.txt')
#operations
f.close()

Do use with as it will automatically close the file for you:

with open('file.txt') as f:
  #operations

5. If you are going to repeat the same function call many times:

Don't:

def function(a, b):
  return a + b

result = 0
a, b = 1, 1

while result < 100:
  result += function(a, b)

Do assign the function to a variable, as it has a better performance:

def function(a, b):
  return a + b

result = 0
a, b = 1, 1

f = function(a, b)
while result < 100:
  result += f

So, did you like the tips? If you have any others, please leave a comment!