Home > Mobile >  Remove n elements after each element in a python list
Remove n elements after each element in a python list

Time:10-19

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

CodePudding user response:

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]

CodePudding user response:

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