-1

I am trying to find the middle element of a list and then take the next 3 items forwards and backwards and make a new list in python.

For example:

lst = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q]
x = my_func(lst)
print(x)
[f, g, h, i, j, k, l]

How would one accomplish this?

I know I can find the middle by doing this: middle_index = (len(lst) - 1)//2 but I am a bit stuck on how to slice it afterwards.

Mojo713
  • 33
  • 2
  • 7

2 Answers2

1

Use list slices and avoid index out of range errors like so:

def middle_slice(lst):
    middle = len(lst) // 2
    return lst[max(0, (middle - 3)) : min(len(lst), (middle + 4))]

for length in [9, 8, 2, 1, 0]:
    print(length, middle_slice(list(range(length))))
# 9 [1, 2, 3, 4, 5, 6, 7]
# 8 [1, 2, 3, 4, 5, 6, 7]
# 2 [0, 1]
# 1 [0]
# 0 []
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
0

Something like this ?

def my_func(lst):
    middle = len(lst)//2
    nlst = lst[middle-3:middle]
    nlst += lst[middle:middle+3]
    return nlst

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q']
x = my_func(lst)
print(x) #==> [f, g, h, i, j, k, l]
dspr
  • 2,383
  • 2
  • 15
  • 19