Iterating Over Every Two Elements in a List

Iterating over every two elements in a list

You need a pairwise() (or grouped()) implementation.

def pairwise(iterable):
"s -> (s0, s1), (s2, s3), (s4, s5), ..."
a = iter(iterable)
return zip(a, a)

for x, y in pairwise(l):
print("%d + %d = %d" % (x, y, x + y))

Or, more generally:

def grouped(iterable, n):
"s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
return zip(*[iter(iterable)]*n)

for x, y in grouped(l, 2):
print("%d + %d = %d" % (x, y, x + y))

In Python 2, you should import izip as a replacement for Python 3's built-in zip() function.

All credit to martineau for his answer to my question, I have found this to be very efficient as it only iterates once over the list and does not create any unnecessary lists in the process.

N.B: This should not be confused with the pairwise recipe in Python's own itertools documentation, which yields s -> (s0, s1), (s1, s2), (s2, s3), ..., as pointed out by @lazyr in the comments.

Little addition for those who would like to do type checking with mypy on Python 3:

from typing import Iterable, Tuple, TypeVar

T = TypeVar("T")

def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]:
"""s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ..."""
return zip(*[iter(iterable)] * n)

Iterating over every two elements in a list in Python

Use itertools.combinations:

>>> import itertools
>>> lst = [1,2,3,4]
>>> for x in itertools.combinations(lst, 2):
... print(x)
...
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

BTW, don't use list as a variable name. It shadows the builtin function/type list.

Iterate every 2 elements from list at a time

You can use iter:

>>> seq = [1,2,3,4,5,6,7,8,9,10]
>>> it = iter(seq)
>>> for x in it:
... print (x, next(it))
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]

You can also use the grouper recipe from itertools:

>>> from itertools import izip_longest
>>> def grouper(iterable, n, fillvalue=None):
... "Collect data into fixed-length chunks or blocks"
... # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
... args = [iter(iterable)] * n
... return izip_longest(fillvalue=fillvalue, *args)
...
>>> for x, y in grouper(seq, 2):
... print (x, y)
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]

Python: For every 2 items in list?

You can use the slice notation:

for item in items[::2]:
print(item)

If you want to iterate pairwise every 2 items, you can do this:

for item1, item2 in zip(items[::2], items[1::2]):
print(item1, item2)

iterate every two elements in the list to do something of the list python

You can create a single iterator and then zip it with itself:

def pairwise(iterable):
return zip(*[iter(iterable)]*2)

which is similar to:

def pairwise(iterable):
i = iter(iterable)
return zip(i, i)

Iterate and select every two elements of a list python

try:

[list(subset) for subset in combinations(my_list, 2)]


[['cc', 'th'],
['cc', 'ab'],
['cc', 'ca'],
['cc', 'cd'],
['th', 'ab'],
['th', 'ca'],
['th', 'cd'],
['ab', 'ca'],
['ab', 'cd'],
['ca', 'cd']]

Iterate by two elements on a list with Java

To achieve the task it's more then enough to use a regular loop and return on each step [curent,curent+1] list elements.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestList
{
public static void main(String args[])
{
ArrayList <String> l = new ArrayList(Arrays.asList("a","b","c","d"));
List al = new TestList().iterateList(l);
al.forEach(System.out::println);

}
public List iterateList(List l)
{

ArrayList<String> al = new ArrayList();
if(l==null || l.size() <= 1)
{
//list size should be not_null and greater then 1 : 2_fine
return null;
}
for(int i=0;i<l.size()-1;i++)
{
String element = l.get(i)+","+l.get(i+1);
al.add(element);
}
return al;
}

Output:

a,b

b,c

c,d

Java - Iterating over every two elements in a list

Just increase i by 2:

for(int i = 0; i < strings.size() - 2; i += 2) {
String first = strings.get(i);
String second = strings.get(i+1);

Iterate over a list, getting multiple items at once

The way that works is usually the proper way...

You could in principle zip the list with a deferred slice of itself:

myList = [1,2,3,4,5]
for one,two in zip(myList, myList[1:]):
print(one,two, sep=",")

Note that zip ends on the shortest given iterable, so it will finish on the shorter slice; no need to also shorten the full myList parameter.

iterating over two values of a list at a time in python

You can use an iterator:

>>> lis = (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08)
>>> it = iter(lis)
>>> for x in it:
... print (x, next(it))
...
669256.02 6117662.09
669258.61 6117664.39
669258.05 6117665.08


Related Topics



Leave a reply



Submit