Loop over list items, except for the last two items (python)

Question:

I want to for loop over a list of 14 items except for the last two items.
Does anybody know if there is a function or command in python which accomplishes this?

Asked By: progammerattempt

||

Answers:

Python lists support slicing like this:

for i in your_list[:-2]
Answered By: Eumel
random_list = [1, 2, 3, 4, 5, 6]

for element in random_list[:-2]:
     print(element)

[Out] :

1 2 3 4
Answered By: Odhian

optionally

items = [] # your 14 item long list here
for i in range(len(items)-2):
    print(items[i])
Answered By: Henok Teklu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.