python - iterate over all pairs of consecutive items with gaps

python iterate over consecutive pairs
python find consecutive repeated values
python find consecutive elements
python iterate over adjacent elements
python iterate over list two items at a time
python get two consecutive pairs from list
python pair elements in list
compare consecutive items in a list python

Given a list:

mylist = [1,6,4,9,2]

I would like to return all pairs of consecutive items within a window. For example, if I want pairs of 3 consecutive items, I could do:

items=3
for x in range(0,len(mylist)-items+1):
    print(mylist[x:x+items])

Which outputs:

[1, 6, 4]
[6, 4, 9]
[4, 9, 2]

This assumes the window size is also 3, so it's only scanning 3 indexes at a time. If I instead want to return all pairs of 3 consecutive items in a window of 4, I would want:

[1, 6, 4]
[1, 6, 9]
[1, 4, 9]
[6, 4, 9]
[6, 4, 2]
[6, 9, 2]
[4, 9, 2]

Is there a simple method to produce these pairs?

Edit to add to Alex's answer below: I ended up using combinations to identify the indexes, then only selecting the indexes starting with zero, like this:

from itertools import combinations
def colocate(mylist,pairs=4,window=6):
    x = list(combinations(range(window),pairs))
    y = [z for z in x if z[0]==0]
    for item in y:
        print(item)

One fairly easy way to do it is to think about it in terms of the index rather than the list items itself. Start with:

import itertools
list(itertools.combinations(range(len(mylist)), 3)

This gets you all the possible index triple combinations in a list with the length of your list. Now you want to filter them to exclude any where the last index is 4 or more away from the first:

list(filter(lambda seq: (seq[-1] - seq[0]) <= 4, itertools.combinations(l, 3)))

This gets you the indeces you want. So now you can get the triples you need based on the indeces:

[[mylist[i] for i in seq] for seq in filter(lambda seq: (seq[-1] - seq[0]) < 4, itertools.combinations(l, 3))]

which produces:

[[1, 6, 4], [1, 6, 9], [1, 4, 9], [6, 4, 9], [6, 4, 2], [6, 9, 2], [4, 9, 2]]

Iterate over all pairs of consecutive items in a list, python iterate over list two items at a time python pair elements in list itertools combinations find consecutive elements in list python python create list of pairs I want to iterate over all pairs of consecutive list items (1,7), (7,3), (3,5), i.e. for i in xrange(len(l) - 1): x = l[i] y = l[i + 1] # do something I would like to do this in a more compact way, like. for x, y in someiterator(l): Is there a way to do do this using builtin Python iterators?

"Combination" is a concept in math related to your question. It does not care about "window of 4" though.

from itertools import combinations

l = [1,6,4,9,2]

for combination in combinations(l, 3):
    print(combination)
(1, 6, 4)
(1, 6, 9)
(1, 6, 2)
(1, 4, 9)
(1, 4, 2)
(1, 9, 2)
(6, 4, 9)
(6, 4, 2)
(6, 9, 2)
(4, 9, 2)

I'm curious why do you want to have a window of 4.

Maybe there is a better way to solve your task at hand?

Python, Sometimes, while working with lists, we need to pair up the like elements in the list print ( "The consecutive element paired list is : " + str (res)) This task can also be achieved using only the zip function which performs the task for all the elements. We use cookies to ensure you have the best browsing experience on our� Iterate over all pairs of consecutive items from a given list Made by the cabbage addicts from the Python room on Stack Overflow . This site is not affiliated with Stack Overflow.

This gets pretty close. There will be some duplicates produced, but that's what set(...) is for at the end... should give you some ideas anyway.

from itertools import combinations, islice, chain

# from itertools examples
def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result    
    for elem in it:
        result = result[1:] + (elem,)
        yield result

mylist = [1,6,4,9,2]

set(chain.from_iterable(combinations(w, 3) for w in window(mylist, 4))) 
{(1, 4, 9), (1, 6, 4), (1, 6, 9), (4, 9, 2), (6, 4, 2), (6, 4, 9), (6, 9, 2)}

Python - Product of consecutive pairs in list, Python – Product of consecutive pairs in list In this, we just iterate the list till last element in skipped manner to get all the pair Works only on Python2. Method #2 : Using zip() + list slicing. zip function can be used to extract pairs over the list and slicing can be used to successively pair the current element with the next one for the efficient pairing.

Iterating over pairs of consecutive items in a list, Iterating over pairs of consecutive items in a list. Iterate over all pairs of consecutive items from a given list. Made by the cabbage addicts from the Python room� An alternative is to explicitly instruct the for loop to iterate over the key:value pairs. The .items() method on a dictionary induces a pseudo-list of (key, value) tuples. The for loop then can iterate over this list, and the bound variable should also be the tuple type:

Lists - Learn Python 3, The number of pairs of equal � Unique elements � Queens � The bowling alley First of all, you can create an empty list (the list with no items, its length is 0), and Python differs from Pascal, where you have to iterate over elements' indexes, which returns a list of strings resulting after cutting the initial string by spaces. The view object returned by.items () yields the key-value pairs one at a time and allows you to iterate through a dictionary in Python, but in such a way that you get access to the keys and values at the same time. If you take a closer look at the individual items yielded by.items (), you’ll notice that they’re really tuple objects.

Minimum Absolute Difference (via Leetcode), Walkthrough of easy python algorithm problem from Leetcode to comparing consecutive values of sorted list # create pairs_list to hold final pairs of O(n) for iteration over all list items to create pairs that meet minimum absolute difference. with decreased time complexity and increase space complexity. [code]list = [1,7,8,4,5,3] for x,y in zip(list[::],list[1::]): print (x,y) #You can add the comparision code here [/code]

Comments
  • "all pairs of 3 consecutive items in a window of 4" is completely add odds with the definition of "consecutive"
  • consecutive items with gaps ? Perhaps it might help if you could take a step back and explain what you need this for.
  • sorry if consecutive isn't the right vocabulary, I'm not looking for combinations. The order matters, but the items don't have to be perfectly next to each other. So it's more like ordered permutations inside a window.
  • i want to count the number of times items appear close to each other, not exactly side by side. So provided some sliding window size, find all pairs that are "in order" in a given pair size.
  • This is basically exactly what I was in the middle of writing. The window recipe selects the input to combinations, combinations gets all ordered non-contiguous selections from within each window. You could preserve order of first appearance for each result by changing set(...) to list(dict.fromkeys(...)) (use collections.OrderedDict.fromkeys prior to Python 3.6), though that assumes that you don't want to see a duplicate even if it comes from unrelated windows.