0

I have a list of numbers (with the length of the list stored in a separate variable) and need to check if any consecutive integers are the same and then print a message if they are. How would I do this?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
James Brightman
  • 857
  • 2
  • 13
  • 23
  • 1
    Save the first value to a variable, then loop through the list check the current value with the variable value, then set the variable to the current value. Print it out whenever the current value is equal to the variable. Try to write some code with this logic, then ask a question with the code if you have problems. – dstudeba Oct 14 '15 at 04:59

4 Answers4

2

try this: Using itertools.groupby

>>> import itertools
>>> your_list = [4, 5, 5, 6]
>>> for x, y in itertools.groupby(your_list):
...     if len(list(y))>=2:
...         print x, "they are consecutive"
... 
5 they are consecutive
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
1

Python has a recipe for doing this called pairwise that you might find interesting:

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

number_list = [1, 2, 2, 3, 4, 4, 5, 5, 5]
print [a for a, b in pairwise(number_list) if a == b]

This will display a list of numbers that have pairs as follows:

[2, 4, 5, 5]
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

Easy to do by zipping the list with a copy of itself offset by one element:

list1 = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
for x, y in zip(list1, list1[1:]):
    if x == y:
        print x

The above code will print 4.

Or if you also want the index:

list1 = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
for index, pair in enumerate(zip(list1, list1[1:])):
    if pair[0] == pair[1]:
        print 'index:', index, 'value:', pair[0]

This will output index: 3 value: 4

zehnpaard
  • 6,003
  • 2
  • 25
  • 40
0

Really not the most optimized way but always funny:

True in [a==b for a,b in zip(l[:-1],l[1:])]

and of course:

if True in [a==b for a,b in zip(l[:-1],l[1:])]:
    print("message")
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46