Rolando
Rolando

Reputation: 62714

Skip first entry in for loop in python?

In python, How do I do something like:

for car in cars:
   # Skip first and last, do work for rest

Upvotes: 289

Views: 401682

Answers (15)

abhitruechamp
abhitruechamp

Reputation: 1

Expanding on @user1063287's comment, you can always do something like:

        for i, car in enumerate(cars):
            if i == 0 or i == len(cars):
                pass
            else:
                print(car)

This would work for both lists and iterables.

Upvotes: 0

Jude
Jude

Reputation: 1

Similar to @maninthecomputer 's answer, when you need to skip the first iteration of a loop based on an int (self._model.columnCount() in my case):

for col in range(self._model.columnCount()):
    if col == 0:
        continue

Put more simply:

test_int = 3

for col in range(test_int):
    if col == 0:
        continue
    print(col)

Provides output:

1
2
3

Upvotes: 0

KurzedMetal
KurzedMetal

Reputation: 12946

This code skips the first and the last element of the list:

for item in list_name[1:-1]:
    #...do whatever

Upvotes: 16

BanikPyco
BanikPyco

Reputation: 868

Good solution for support of itertools.chain is to use itertools.islice in order to take a slice of an iterable:

your_input_list = ['list', 'of', 'things']
for i, variant in list(itertools.islice(enumerate(some_function_that_will_output_itertools_chain(your_input_list)), 1, None)):
   """
   # No need for unnecessary conditions like this:
   if i == 0:
      continue
   """
   variant = list(variant) # (optional) converting back to list
   print(variant)

Upvotes: -1

Roee Shenberg
Roee Shenberg

Reputation: 1547

The best way to skip the first item(s) is:

from itertools import islice
for car in islice(cars, 1, None):
    pass
    # do something

islice in this case is invoked with a start-point of 1, and an end point of None, signifying the end of the iterable.

To be able to skip items from the end of an iterable, you need to know its length (always possible for a list, but not necessarily for everything you can iterate on). for example, islice(cars, 1, len(cars)-1) will skip the first and last items in cars.

Upvotes: 54

Abhijit
Abhijit

Reputation: 63787

To skip the first element in Python you can simply write

for car in cars[1:]:
    # Do What Ever you want

or to skip the last elem

for car in cars[:-1]:
    # Do What Ever you want

You can use this concept for any sequence (not for any iterable though).

Upvotes: 550

Tono Kuriakose
Tono Kuriakose

Reputation: 896

Example:

mylist=['one','two','three','four','five']
for i in mylist[1:]:
   print(i)

In python index start from 0, We can use slicing operator to make manipulations in iteration.

for i in range(1,-1):

Upvotes: 6

maninthecomputer
maninthecomputer

Reputation: 512

Here's my preferred choice. It doesn't require adding on much to the loop, and uses nothing but built in tools.

Go from:

for item in my_items:
  do_something(item)

to:

for i, item in enumerate(my_items):
  if i == 0:
    continue
  do_something(item)

Upvotes: 6

dmb
dmb

Reputation: 298

I do it like this, even though it looks like a hack it works every time:

ls_of_things = ['apple', 'car', 'truck', 'bike', 'banana']
first = 0
last = len(ls_of_things)
for items in ls_of_things:
    if first == 0
        first = first + 1
        pass
    elif first == last - 1:
        break
    else:
        do_stuff
        first = first + 1
        pass

Upvotes: -3

pylang
pylang

Reputation: 44615

The more_itertools project extends itertools.islice to handle negative indices.

Example

import more_itertools as mit

iterable = 'ABCDEFGH'
list(mit.islice_extended(iterable, 1, -1))
# Out: ['B', 'C', 'D', 'E', 'F', 'G']

Therefore, you can elegantly apply it slice elements between the first and last items of an iterable:

for car in mit.islice_extended(cars, 1, -1):
    # do something

Upvotes: 1

dwitvliet
dwitvliet

Reputation: 7691

An alternative method:

for idx, car in enumerate(cars):
    # Skip first line.
    if not idx:
        continue
    # Skip last line.
    if idx + 1 == len(cars):
        continue
    # Real code here.
    print car

Upvotes: 2

Abhijit
Abhijit

Reputation: 63787

Based on @SvenMarnach 's Answer, but bit simpler and without using deque

>>> def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
>>> list(skip(range(10), at_start=2, at_end=5))
[2, 3, 4]

Also Note, based on my timeit result, this is marginally faster than the deque solution

>>> iterable=xrange(1000)
>>> stmt1="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)
list(skip(iterable,2,2))
    """
>>> stmt2="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()
list(skip(iterable,2,2))
        """
>>> timeit.timeit(stmt = stmt1, setup='from __main__ import iterable, skip, itertools', number = 10000)
2.0313770640908047
>>> timeit.timeit(stmt = stmt2, setup='from __main__ import iterable, skip, itertools, collections', number = 10000)
2.9903135454296716

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 602745

Here is a more general generator function that skips any number of items from the beginning and end of an iterable:

def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()

Example usage:

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]

Upvotes: 32

Andrew Jaffe
Andrew Jaffe

Reputation: 27097

Well, your syntax isn't really Python to begin with.

Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container. In this case, the container is the cars list, but you want to skip the first and last elements, so that means cars[1:-1] (python lists are zero-based, negative numbers count from the end, and : is slicing syntax.

So you want

for c in cars[1:-1]:
    do something with c

Upvotes: 3

agf
agf

Reputation: 176980

The other answers only work for a sequence.

For any iterable, to skip the first item:

itercars = iter(cars)
next(itercars)
for car in itercars:
    # do work

If you want to skip the last, you could do:

itercars = iter(cars)
# add 'next(itercars)' here if you also want to skip the first
prev = next(itercars)
for car in itercars:
    # do work on 'prev' not 'car'
    # at end of loop:
    prev = car
# now you can do whatever you want to do to the last one on 'prev'

Upvotes: 336

Related Questions