Consecutive values?
<p>Learning python, but having trouble telling function to find consecutive locations with same values. When I run the code, there's no errors but gives out the incorrect output. Suggestions on what to change?</p>

<pre><code>def same_values(xs):
    same = False
    for i in (xs):
        if xs == xs[1:]:
            same = True
    else:
        return same
same_values('Misses') # This should return as true
</code></pre>

<p>So you are looking for a consecutive pair in the list and returning true if you find one. </p>

<pre><code>def same_values(xs):
    for i in range(len(xs)-1):
        if xs[i] == xs[i+1]:
            return True
    return False

&gt;&gt;&gt; same_values('misses')
True
&gt;&gt;&gt; same_values('mises')
False
</code></pre>

<p>Would give you the correct answer.<br>
However python has a powerful iterator algebra. The advantage of this is that it would work with iterators (iterators don't generally support <code>len()</code>) as well as lists:</p>

<pre><code>import itertools as it

def same_values(xs):
    a, b = it.tee(xs)
    next(b, None)
    return any(x == y for x, y in zip(a, b))
</code></pre>

<p>This pattern is described in the <code>itertools</code> recipes as <a href="https://docs.python.org/3.5/library/itertools.html?highlight=pairwise" rel="nofollow"><code>pairwise</code></a>:</p>

<pre><code>import itertools as it

def pairwise(iterable):
    "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = it.tee(iterable)
    next(b, None)
    return zip(a, b)

def same_values(xs):
    return any(x == y for x, y in pairwise(xs))
</code></pre>

<p>For example to check if any 2 consecutive lines in a file are the same (this wouldn't work with the <code>list</code> version):</p>

<pre><code>with open('somefile') as f:
    print(same_values(f))
</code></pre>

python function