3
mylist = [{'a':1,'b':2},{'a':3,'b':'10'},.....]
I want to do some special operations for the last itemin  loop (iterarale), what to do?

for item in mylist:
   do some operations for all items
   #I want to execute the next statement only for last item

   last_b = item[b] 

last_b

What is the best method to do this(with out an if statement)

Jisson
  • 3,566
  • 8
  • 38
  • 71

3 Answers3

8

item remains in scope at the end of the loop, and conveniently is the last item, so you just need to dedent that line

for item in mylist:
    # do some operations for all items
last_b = item[b] 
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
3

Try this:

for i in range(len(my_list)-1):
     #do stuff till last before element, where i will be the index of the list

my_list[last]=#something

This will do seperate iteration only for the last element in the list

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
1

Well if it is the last iteration of the loop, then why don't you do that outside the loop itself.

IcyFlame
  • 5,059
  • 21
  • 50
  • 74