0

I have been posed the following question:

Make a new function named first_and_last_4. It'll accept a single iterable but, this time, it'll return the first four and last four items as a single value.

Here is my code:

def first_and_last_4(x):
    first_4 = x[:4]
    last_4 = x[-4:]
    return (first_4.extend(last_4))

I have also tried to simplify this:

def first_and_last_4(x):
    return x[:4] + x[-4:]

Error:

Bummer: Couldn't find first_4

Can you help?

sachin dubey
  • 735
  • 8
  • 28
Samuel Adjei
  • 9
  • 1
  • 5

2 Answers2

1

Simply try this:

def first_and_last_4(x):
    return x[:4]+x[-4:] #you had indentation problem here
Taohidul Islam
  • 5,008
  • 3
  • 23
  • 37
0

Be careful. An iterable need not be a list, so list slicing should not be assumed as an acceptable solution. To extract the elements you require, you can create an iterator via built-in iter:

  • For the first n elements, you can use a list comprehension over range(n).
  • For the last n elements, you can use collections.deque and set maxlen=n.

Here's an example:

from itertools import islice
from collections import deque

def first_and_last_n(x, n=4):
    iter_x = iter(x)
    first_n = [next(iter_x) for _ in range(n)]
    last_n = list(deque(iter_x, maxlen=n))
    return first_n + last_n

res = first_and_last_n(range(10))

print(res)

[0, 1, 2, 3, 6, 7, 8, 9]
jpp
  • 147,904
  • 31
  • 244
  • 302