• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Data Dependence

Data Dependence

Learn about software development. Covering topics such as Coding in Python and JavaScript, developer productivity and more.

  • Home
  • Top Resources
  • Who Are You?
  • Show Search
Hide Search
You are here: Home / Programming / How to Write Beautiful Code with Pythonic Idioms | For Loops

How to Write Beautiful Code with Pythonic Idioms | For Loops

· · 1 Comment

Although not the first language I picked up, I’ve really taken a liking to Python, especially recently. I’ve tried out many languages and Python is one of the languages that I find the most fun to program in. One of the reasons I enjoy programming in it so much is that Python code is neat, minimalistic and beautiful.
The syntax of the language is fantastic, but when you start changing the way you write code to be more ‘pythonic’, that’s when the real beauty kicks in. Pythonic code is code that makes use of the multitudes of ‘python idioms’ that exist, a python idiom being a specific way to code that is, well… pythonic.

This is the first in a series of posts on common pythonic idioms. Let’s kick it off with for loops.

HOW NOT TO WRITE FOR LOOPS (AND THEIR PYTHONIC COUNTERPARTS)

For loops are used a lot, and the following pythonic idioms for these common uses are often actually faster than their non-pythonic counterparts. Not to mention they are extremely readable.

Note that I refer to a ‘sequence’ a lot in this post. A sequence is a python type; a list, tuple or range object.

LOOPING OVER A RANGE OF VALUES

One common use of a for loop is to iterate over a range of values.

#This is how not to iterate over a range of values
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    #do stuff
#This is how to iterate over a range of values
for i in range(11):
    #do stuff

As you can see here the range() function is used. It loops up to but not including the value you pass it. You can provide just a stop value or a start, end and optionally step value too. For more information on the range function, take a look at the Python documentation.

LOOPING OVER A SEQUENCE, USING BOTH THE INDEXES AND VALUES

Another common use of a for loop is to loop over a sequence, doing things with its index and value pairs.

#This is not how to iterate over a list and use indexes and values
for i in range(len(array)):
    #do stuff with i
    #do stuff with array[i]
#This is how to iterate over a list and use indexes and values
for i, val in enumerate(array):
    #do stuff with i
    #do stuff with val

The enumerate() function returns a tuple of the current index and value pair for each iteration of the for loop which are unpacked into the two variables before it; in this case i and val. You can also pass an offset value to enumerate to start the index count from a number other than 0. For more information on the enumerate function, take a look at the Python documentation.

LOOPING OVER A SEQUENCE IN REVERSE ORDER

The final common use of a for loop that we will go over in this post is looping over a sequence in reverse order.

#This is not how to iterate over a list in reverse order
for val in range(len(array) - 1, -1, -1):
    #do stuff
#This is how to itereate over a list in reverse order
for val in reversed(array)
    #do stuff

The reversed() function simply iterates over a sequence backwards. There’s not really much more to know about it, but if you would like to read more about it, take a look at the Python documentation.

So there we have it, three common pythonic idioms for for loops. Hopefully you have learnt something from this as I did and gained the power to write more pythonic code.

This was the first in a series of posts on common pythonic idioms.

Don't forget to share and follow!

Remember, don't forget to share this post so that other people can see it too! Also, make sure you subscribe to this blog's mailing list and follow me on Twitter so that you don't miss out on any useful posts!

I read all comments, so if you have something to say, something to share or questions and the like, leave a comment below!

‘Ello, I’m Jamal – a Tokyo-based, indie-hacking, FinTech software developer with a dependence on data.

I write Shakespeare-grade code, nowadays mostly in Python and JavaScript and productivity runs in my veins.

I’m friendly, so feel free to say hello!

Twitter is the best place for a chat.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Pocket (Opens in new window)

Related

Programming for loops, idioms, python, pythonic

Primary Sidebar

LEVEL UP with the Data Dependence Newsletter! Subscribe!


Top Posts & Pages

  • How to Find Unclosed Tags and Brackets Using a Stack
  • How to Build a GUI in Python 3.5
  • Mocking in Python - How to Bypass Expensive and External Code Within Your Tests
  • How to Logically Group Your Python Code into Modules
  • A Quick Guide to Slicing in Python - Become a Python Ninja

Data Dependence

Copyright © 2023 · Monochrome Pro on Genesis Framework · WordPress · Log in

  • Home
  • Top Resources
  • Who Are You?