[Tutor] modification to a list
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Apr 22 14:12:17 EDT 2020
On 22/04/2020 16:59, Subhash Nunna wrote:
> Please try this:
>
> def skip_elements(elements):
> new_list = [ ]
> a = len(elements)+1
You don't want to add one. Just use len()
> if a==1:
> return new_list
a==1 implies an empty list using your code above.
> else:
> for i in range(0, a):
This will push index past the end of the list.
If the list is [1,2,3] then len() returns 3 and a is set to 4
Now range(0,4) returns [0,1,2,3]
But there is no index 3.
> if i%2==0:
> new_list.append(elements[i])
> return new_list
It is because of the difficulty in getting indexes right
that we prefer to use the foreach style of processing
in Python:
for item in elements
And if you really need the index(rare) you can use enumerate:
for index,item in enumerate(elements):
These guarantee never to over-run your collection.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list