How to iterate through two lists with one of them shifted?

python

Solution

slice the first list with `[1:]`:

for elem1, elem2 in zip(unigram_mixture_list[1:], bigram_mixture_list):

You got everything else exactly right

Note that if the lists were the same length, but now truncated because you've shortened one, you have a couple choices:

- slice the second list to remove the tail: `[:-1]`

- replace `zip` with `itertools.izip_longest` (after `import itertools`)

Example with `izip_longest`:

import itertools

# ~~~ other code ~~~ #

for elem1, elem2 in itertools.izip_longest(unigram_mixture_list[1:], bigram_mixture_list):
    print elem1, elem2

Edit: In python 3, `izip_longest` was renamed `zip_longest`, so use that instead.

Problem

My question is how do you start one list at the next index when iterating? ``` for elem1, elem2 in zip(unigram_mixture_list, bigram_mixture_list): print elem1, elem2 ``` I want to start looping through `elem1` one index ahead. How would I achieve this in python?

Original source