Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

loops

list

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
like image 614
Dap Avatar asked Jan 08 '14 21:01

Dap


People also ask

How do you iterate through 1 in Python?

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.

How do you skip items in For loop?

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.

How do you skip the first item in a For loop?

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 .


1 Answers

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
like image 149
jonrsharpe Avatar answered Nov 15 '22 18:11

jonrsharpe