Supreme1707
Supreme1707

Reputation: 178

Remove n elements after each element in a python list

I want to remove n elements after each element in a list. Example with n = 7:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]  # unmodified list
[1, 9, 17]  # final list

I tried this approach but it failed, removing every alternate element from the list for some reason.

# cases is a list with over 600 numbers
case_count = 0
case_index = 0

for case in cases:
    print(case_count)
    print(case_index)
    if case_count != 7:
        popped = cases.pop(case_index)
        print(case_index)
        case_count += 1
    else:
        print("Case count equal to 7")
        case_count = 0
    case_index += 1

Upvotes: 1

Views: 245

Answers (2)

mozway
mozway

Reputation: 260490

So, basically you want to slice every eighth element?

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
l[0::8]

output: [1, 9, 17]

Upvotes: 6

d.b
d.b

Reputation: 32548

n = 7
[arr[i] for i in range(0, len(arr), n + 1)]
# [1, 9, 17]

Upvotes: 1

Related Questions