2

I have a list that will always contain an even number of elements and I want to iterate over this list to create a new list containing lists of each 2 consecutive numbers in the list.

For example:

first_list = [1,2,3,4,5,6,7,8]
second_list = [[1,2], [3,4], [5,6], [7,8]]

When I iterate over the list I cannot figure out how to select consecutive pairs. I've tried a million variations, and this is the closest that I've come.

first_list = [1,2,3,4,5,6,7,8]    
second_list = []

pairs = 1

for item in range(len(first_list) - pairs): 
    second_list.append([firs_list[item],first_list[item + pairs]])
print second list

[[1, 5], [5, 7], [7, 6], [6, 2], [2, 3], [3, 4], [4, 8]]

Is there some way that I have have the for loop iterate over every other item?

stevec
  • 155
  • 1
  • 3
  • 10
  • ^ The top answer there is a general solution which will work neatly for your problem. (Just set or hard-code n=2 and use the list comprehension version.) – Two-Bit Alchemist Mar 28 '16 at 20:27

3 Answers3

1

This code should do that:

first_list = [1,2,3,4,5,6,7,8]     
second_list = []
for i in range(0,len(first_list)-1,2):
   if first_list[i]+1==first_list[i+1]:
      second_list.append([first_list[i],first_list[i+1]])
print second_list

output:

[[1, 2], [3, 4], [5, 6], [7, 8]]
Denis
  • 1,219
  • 1
  • 10
  • 15
  • 1
    This is interesting but it's a different result than OP asked for. Notice your pairs overlap ([1, **2**], [**2**, 3]) while the originals don't. – Two-Bit Alchemist Mar 29 '16 at 12:14
  • Looks good now. In fact, it's the only answer I'll upvote because of your if statement. I was going to say it wasn't necessary, but re-reading the post, I think you're the only person who noticed (and correctly implemented) that requirement! (You might want to put an `or` check in case they're in reversed order, like `(7, 6)` though.) – Two-Bit Alchemist Mar 29 '16 at 19:01
0

You can combine functions from itertools module. Without the outermost map it returns a list of tuples and map converts it to a list of lists:

>>> from itertools import cycle, compress, izip
>>> 
>>> lst = [1,2,3,4,5,6,7,8]
>>> map(list, izip(compress(lst, cycle([1, 0])), compress(lst, cycle([0, 1]))))
[[1, 2], [3, 4], [5, 6], [7, 8]]
pkacprzak
  • 5,537
  • 1
  • 17
  • 37
0

You were almost there. You needed to use more arguments for range.

Simple fix:

for item in range(0, len(first_list) - 1, 2):
    second_list.append([first_list[item],first_list[item + 1]])
print second_list

The arguments to range are range(start, stop[, step]) and tell it to start from zero up to length-1 and use a step of two.

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88