Search code examples
pythonlistpython-itertools

Elegant / Efficient way of getting one element and the following in an iterable


So I have a question, I have an iterable (string or list here) like string = "ABCDEFG" and I want to ouput something like

A-B
B-C
C-D
...
F-G

So I know this works (forgot to handle indexError, but whatever) but it's pretty ugly...

for i in range(len(myString)):
    element1 = myString[i]
    element2 = myString[i+1]
    print("theshit")

Is there a way of doing that in a more elegant/pythonic way ? I think itertools can be a solution but I don't know how it works..

By the way, I need myString only for this loop so maybe generators (don't know how to use that too, I'm still learning)

Thanks :)


Solution

  • itertools.izip might be useful here if you zip your sequence with the tail of the sequence (which you can get using itertools.islice):

    >>> from itertools import islice, izip
    >>> iterable = "abcdefg"
    >>> for x in izip(iterable, islice(iterable, 1, None)): print x
    ...
    ('a', 'b')
    ('b', 'c')
    ('c', 'd')
    ('d', 'e')
    ('e', 'f')
    ('f', 'g')