Skip to content
Advertisement

How to treat the last element in list differently in Python?

I need to do some special operation for the last element in a list. Is there any better way than this?

array = [1,2,3,4,5] 
for i, val in enumerate(array): 
  if (i+1) == len(array): 
    // Process for the last element 
  else: 
    // Process for the other element 

Advertisement

Answer

JavaScript

If you don’t want to make a copy of list, you can make a simple generator:

JavaScript

Another definition for notlast:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement