List containing only every second second pair of elements

Viewed 1013

I am new to python and so I am experimenting a little bit, but I have a little problem now.

I have a list of n numbers and I want to make a new list that contains only every second pair of the numbers.

So basically if I have list like this

oldlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

then I want that the new list looks like this

newlist = [3, 4, 7, 8]

I already tried the slice() function, but I didn't find any way to make it slice my list into pairs. Then I thought that I could use two slice() functions that goes by four and are moved by one, but if I merge these two new lists they won't be in the right order.

8 Answers

If you enumerate the list, you'd be taking those entries whose indices give either 2 or 3 as a remainder when divided by 4:

>>> [val for j, val in enumerate(old_list) if j % 4 in (2, 3)]

[3, 4, 7, 8]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [a[i]  for i in range(len(a)) if i%4 in (2,3)]

# Output: b = [3, 4, 7, 8]

Here, we use the idea that the 3rd,4th,7th,8th..and so on. indices leave either 2 or 3 as the remainder when divided by 4.

first_part = oldList[2::4] # every 4th item, starting from the 3rd item
second_part = oldList[3::4] # every 4th item starting from the 4th item

pairs = zip(first_part, second_part)
final_result = chain.from_iterable(pairs)

Break this problem in to parts.

first = oldlist[2::4]
second = oldlist[3::4]
pairs = [(x, y) for x, y in zip(first, second)]

Now unwrap the pairs:

newlist = [x for p in pairs for x in p]

Combining:

newlist = [z for p in [(x, y) for x, y in zip(oldlist[2::4], oldlist[3::4])] for z in p]

I would firstly divide original list into two lists, with odd and even elements. Then iterate over zip of them.

old = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list()
part1, part2 = old[::2], old[1::2]
for i, z in enumerate(zip(part1,part2)):
    if i % 2 == 0:
        result.extend(z)

You could use a double range:

oldlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
newlist = []
for i,j in zip(range(2, len(oldlist), 4), range(3, len(oldlist), 4)):
    newlist += [oldlist[i], oldlist[j]]

#> newlist: [3, 4, 7, 8]
import more_itertools
oldlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[*more_itertools.interleave(oldlist[2::4], oldlist[3::4])]
# [3, 4, 7, 8]

oldlist[2::4], oldlist[3::4]: slice 4th item [*more_itertools.interleave(...)]: interleave the two above and convert back to a list

Here is what I have come up with:

oldList = list(range(1,10))
newList = []
for i in oldList:
    if (i%2 == 0) and (i%4 != 0):
        try:
            newList.append(i+1)
            newList.append(i+2)
        except IndexError:
            break

Result:

>>> newList
[3, 4, 7, 8]
Related