Instant Search

List Iteration Tricks

Hi , so now suppose you have an list in python :

 

you want to add 1 to each element of list so if you try like this :

You will get this output:

Because its adding 1 to each iterator value.

First what is i here ?

So first let’s print i and know what is exactly i is here ?

output

 

i is iterator it means it will start from 0,1,2,3,4 till length of list if we give statement like  :

Now that’s why (i+1) will add 1 to each iterator now to value of list.

Now try something like this :

it will add “1” to each value of index value :

output:

You have to know

 

Now lets try something more to clear this doubt :

what do you expect ?

 

If you are thinking it will add one and 4 and then print list[5] value then you are wrong it will add index 1 value to index 4 value :

index 1 value : 8

index 6 value: 6

list[1]+list[4] is 14

take a look of this example too:

 

and now this :

now its not adding with index value its adding 1 to iterator value and then it will print [3+1] =list[4] element

if you try this:

it will give error :

why? because as i said “i” is iterator value so its adding one to iterator and then printing that no of index

what we have:

Screenshot 2016-10-18 18.45.53

so first list[i+1[ will print list[0+1] which is  list[1] value 8
second it will add [1+1] which is list [2] value 6

———

———-

———

at last it will add [7+1] which is list[8] but there is no 8th element in list.

 

Now here is the trick on which this post is based on :

You can remove error by try and catch exception but i am going to tell little trick:

whenever you need to add in iterator in loop then just subtract one in loop argument i mean always iterate less than len of list so what i meant is :

you can see i have did something (len(list)-1 which is iterating less than one of total index of list now if we run we will not get error :

output :

because it will always iterate less one then the size of list.

suppose list is list=[1,2]

if we don’t subtract then when it iterate two times which iterate values 0 and 1 for second iteration  i=1   so it will try to find [i+1] which is  index[2] and there is no [2] in list and if we subtract one then it will iterate one time   which is i=0 and now [i+1] which is i[0+1] so it will always in limit .

 

we can generate list with range function:

 

another trick about return and calling function . see this example in example i am not calling function simply i am calling function with return statement :

Let’s talk about nested loops :

for each i it will iterate in range from 0 to i 

 

it will check each element of i with each value between 0 to i

Leave a Reply

Your email address will not be published. Required fields are marked *