[Python] Why does my Python for loop skip the last element in a list?

Discussão em 'Python' iniciado por Stack, Setembro 3, 2025.

  1. Stack

    Stack Membro Participativo

    I’m working on a simple Python program where I want to print all the items in a list. Here’s my code:

    numbers = [1, 2, 3, 4]
    for i in range(len(numbers)-1):
    print(numbers)


    Problem: The code is only printing:

    1
    2
    3


    But it is skipping the last number 4.

    What I tried:

    I checked my list, and all items are correct.

    I tried printing len(numbers) and it shows 4, which is expected.

    I was expecting the loop to print all four numbers (1, 2, 3, 4).

    Question: Why is my loop skipping the last element, and how can I fix it to include all items?

    I tried looping through the list using range(len(numbers)-1). I expected the loop to print all 4 numbers in the list, but it only printed 3 numbers and skipped the last one.

    Continue reading...

Compartilhe esta Página