Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 435119
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T20:20:38+00:00 2026-05-12T20:20:38+00:00

How can I treat the last element of the input specially, when iterating with

  • 0

How can I treat the last element of the input specially, when iterating with a for loop? In particular, if there is code that should only occur "between" elements (and not "after" the last one), how can I structure the code?

Currently, I write code like so:

for i, data in enumerate(data_list):
    code_that_is_done_for_every_element
    if i != len(data_list) - 1:
        code_that_is_done_between_elements

How can I simplify or improve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T20:20:39+00:00Added an answer on May 12, 2026 at 8:20 pm

    Most of the times it is easier (and cheaper) to make the first iteration the special case instead of the last one:

    first = True
    for data in data_list:
        if first:
            first = False
        else:
            between_items()
    
        item()
    

    This will work for any iterable, even for those that have no len():

    file = open('/path/to/file')
    for line in file:
        process_line(line)
    
        # No way of telling if this is the last line!
    

    Apart from that, I don’t think there is a generally superior solution as it depends on what you are trying to do. For example, if you are building a string from a list, it’s naturally better to use str.join() than using a for loop “with special case”.


    Using the same principle but more compact:

    for i, line in enumerate(data_list):
        if i > 0:
            between_items()
        item()
    

    Looks familiar, doesn’t it? 🙂


    For @ofko, and others who really need to find out if the current value of an iterable without len() is the last one, you will need to look ahead:

    def lookahead(iterable):
        """Pass through all values from the given iterable, augmented by the
        information if there are more values to come after the current one
        (True), or if it is the last value (False).
        """
        # Get an iterator and pull the first value.
        it = iter(iterable)
        last = next(it)
        # Run the iterator to exhaustion (starting from the second value).
        for val in it:
            # Report the *previous* value (more to come).
            yield last, True
            last = val
        # Report the last value.
        yield last, False
    

    Then you can use it like this:

    >>> for i, has_more in lookahead(range(3)):
    ...     print(i, has_more)
    0 True
    1 True
    2 False
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there any way I can make so that I can treat a file
I need an interface to mongodb by which I can treat data in a
How can we treat a Mysql table as a limited FIFO buffer (Queue). Objectives
I'm a little confused between a unichar and a char. Can I treat unichar's
I was just thinking, as you can treat Blocks like objects if I create
If I have a variable containing a string, is there a way that I
I do like the way I can treat lists in Python. It does any
The List object has the mkString method that will can convert to a string
Is there a well-known parser description language (like Backus-Naur) that allows for repetitions where
Can anyone let me know how can we change the value of kendo combobox

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.