Samuel Adjei
Samuel Adjei

Reputation: 9

Slicing an iterable - Function not working(python)

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?

Upvotes: 0

Views: 284

Answers (2)

jpp
jpp

Reputation: 164623

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]

Upvotes: 0

Taohidul Islam
Taohidul Islam

Reputation: 5414

Simply try this:

def first_and_last_4(x):
    return x[:4]+x[-4:] #you had indentation problem here

Upvotes: 1

Related Questions