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
                Use n+1 in Place of n in the range() Function to Start the for Loop at an Index 1 in Python. This method can be implemented by using the start value as 1 and the stop value as n+1 instead of default values 0 and n , respectively.
You can use the continue statement if you need to skip the current iteration of a for or while loop and move onto the next iteration.
Use iter() and next() to skip first element of a for-loop User iter(object) to return an iterable for any iterable object . Call next(iterator) on iterator as the iterable for object to skip the first element of iterator .
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With