简体   繁体   中英

How to do something only to the first item within a loop in python?

I want to do something different to the the first item in a list. What is the most pythonic way of doing so?

for item in list:
    # only if its the first item, do something

    # otherwise do something else

A few choices, in descending order of Pythonicity:

for index, item in enumerate(lst): # note: don't use list
    if not index: # or if index == 0:
        # first item
    else:
        # other items

Or:

first = True
for item in lst:
    if first:
        first = False
        # first item 
    else:
        # other items 

Or:

for index in range(len(lst)):
    item = lst[i]
    if not index:
        # first item
    else:
        # other items

You can create an iterator over the list using iter(), then call next() on it to get the first value, then loop on the remainder. I find this a quite elegent way to handle files where the first line is the header and the rest is data, ie

list_iterator = iter(lst)

# consume the first item
first_item = next(list_iterator)

# now loop on the tail
for item in list_iterator:
    print(item)
do_something_with_first_item(lst[0])
for item in lst[1:]:
    do_something_else(item)

Or:

is_first_item = True
for item in lst:
    if is_first_item:
        do_something_with_first_item(item)
        is_first_item = False
    else:
        do_something_else(item)

Do not use list as a variable name, because this shadows the built-in function list() .

The enumerate -based solution in jonrsharpe's answer is superior to this. You should probably use that instead.

Use a flag that you change after processing the first item. For example:

first = True
for item in my_list:
    if first:
        # Processing unique to the first item
        first = False
    else:
        # Processing unique to other items
    # Shared processing

You could also just process the first item:

first = my_list.pop(0)
# Process first
for item in my_list:
    # Process item

# Add the first item back to the list at the beginning
my_list.insert(0, first)

jonrsharpe's first version using enumerate is clean and simple, and works with all iterables:

for index, item in enumerate(lst):
    if not index:
        do_something_with_first_item(item)
    else:
        do_something_else(item)

senshin's first solution using lst[0] and lst[1:] is even simpler, but only works with sequences:

do_something_with_first_item(lst[0])
for item in lst[1:]:
    do_something_else(item)

You can get the best of both worlds by using iterators directly:

it = iter(lst)
do_something_with_first_item(next(it))
for item in it:
    do_something_else(item)

But, despite being the best of both worlds, it's actually not quite as simple as either. This is only clearly worth doing if you know you have an iterator (so you can skip the first line), or you need one anyway to do itertools and genexpr and similar stuff to (so you were already going to write the first line). Whether it's worth doing in other cases is more of a style issue.

I want to do something different to the the first item in a list. What is the most pythonic way of doing so?

for item in list:
    # only if its the first item, do something

    # otherwise do something else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM