Python – Traverse List except Last Element

Python Traverse List except Last Element

Python - Traverse List except Last Element

To traverse Python List except for the last element, there are two ways.

  • Get a copy of the list without last element and traverse this list using a looping statement.
  • Use index and length of list to traverse the list until the last element, but not executing the loop for the last element.

In this tutorial, we will go through examples for these two approaches.

Examples

1. Traverse List except last element using Slicing

In this example, we will use the first approach that we mentioned above.

We can use slicing to get the list without last element, and then use for loop or while loop to traverse the elements.

Python Program

source_list = [8, 4, 7, 3, 6, 1, 9]
for x in source_list[:-1]:
    print(x)
Run Code Copy

Output

8
4
7
3
6
1

We have traversed the list except for the last element.

2. Traverse List except last element using index

In this example, we will use the second approach that we mentioned during introduction.

We can use index to access Python List elements, and use while loop to traverse through them. To traverse through list except for the last element, we have to check the condition if the index is less than the list length by one, and stop traversing when the condition fails.

Python Program

source_list = [8, 4, 7, 3, 6, 1, 9]

index = 0
while index < len(source_list) - 1:
    print(source_list[index])
    index += 1
Run Code Copy

Output

8
4
7
3
6
1

Summary

In this tutorial of Python Examples, we learned how to traverse through Python List except for the last element, using slicing and index.

Related Tutorials

Code copied to clipboard successfully 👍