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

list, loops, python

Solution

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

Problem

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 ```

Original source

Related problems