Jeff
Jeff

Reputation: 4413

Python -- Do things to current element and next element in list?

I want to preform a function, let's say print, on the current and next element in the list. How do you do this without getting an error when you get to the last element in the list?

some_list = ["one", "two", "three"]

desired output:

curr_item: "one"
next_item: "two"

curr_item: "two"
next_item: "three"

curr_item: "three"
next_item: "end"

What I have tried:

index = 0
for item in list_name[:-1]:
    print item, list_name[index+1]
    index = index+1

Upvotes: 5

Views: 7654

Answers (8)

use a linked list to evaluate the list

class Node:
    def __init__(self, dataval=None):
       self.dataval = dataval
       self.nextval = None
       self.previousval=None

class LinkedList:
    def __init__(self):
       self.headval = None

    def listprint(self):
       node = self.headval
       while node is not None:
           if node.previousval!=None:
                print("Previous Node",node.previousval.dataval)
           else:
                print("Previous Node is None")
           print("CurrentNode", node.dataval)
           print("\n")
           node = node.nextval        
    
list1 = LinkedList()
some_list = ["one", "two", "three"]
for item in some_list:
    if list1.headval==None:
        currentNode=Node(item)
        list1.headval = currentNode
        currentNode.previousval=None
        previousNode=currentNode
    else:
        currentNode=Node(item)
        currentNode.previousval=previousNode
        previousNode.nextval=currentNode
        previousNode=currentNode
    
list1.listprint()

output:

Previous Node is None
CurrentNode one

Previous Node one
CurrentNode two

Previous Node two
CurrentNode three

Upvotes: 0

Malintha
Malintha

Reputation: 4766

One line solution

[(cur, nxt) for cur, nxt in zip(some_list, some_list[1:])]

Upvotes: 1

Bruno
Bruno

Reputation: 695

here you go:

some_list = ["one", "two", "three"]

for f, r in enumerate(some_list):
try:
    print('curr_item : ',some_list[f])
    print('next_item : ',some_list[f+1])
    print()

except IndexError :
    pass

Output:

curr_item :  one
next_item :  two

curr_item :  two
next_item :  three

curr_item :  three

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142126

You can use the pairwise recipe from itertools, something like:

from itertools import izip_longest, tee

def pairwise(iterable):
    fst, snd = tee(iterable)
    next(snd, None)
    return izip_longest(fst, snd, fillvalue='end')

for fst, snd in pairwise(['one', 'two', 'three']):
    print fst, snd

#one two
#two three
#three end

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

You can use itertools.izip_longest for this:

>>> from itertools import izip_longest
>>> some_list = ["one", "two", "three"]
>>> for x, y in izip_longest(some_list, some_list[1:], fillvalue='end'):
    print 'cur_item', x
    print 'next_item', y


cur_item one
next_item two
cur_item two
next_item three
cur_item three
next_item end

Upvotes: 4

Hyperboreus
Hyperboreus

Reputation: 32429

You can zip the list:

some_list = ["one", "two", "three"]

for cur, nxt in zip (some_list, some_list [1:] ):
    print (cur, nxt)

Or if you want the end value:

for cur, nxt in zip (some_list, some_list [1:] + ['end'] ):
    print (cur, nxt)

Upvotes: 14

venpa
venpa

Reputation: 4318

We can iterate till second last element using list index. List index could be calculated using len and range function as follows:

for i in range(len(some_list)-1):
   print some_list[i], some_list[i+1]

Output:

one two
two three

Upvotes: 2

Ruben Bermudez
Ruben Bermudez

Reputation: 2323

You can try something like:

for i in range(len(some_list)):
    print("curr_item: " + some_list[i])
    if i < len(some_list)-1:
        print("next_item: " + some_list[i+1])
    else:
        print('next_item: "end"')

Upvotes: 0

Related Questions