[Tutor] modification to a list

Alan Gauld alan.gauld at yahoo.co.uk
Sat Apr 25 10:09:45 EDT 2020


On 25/04/2020 05:03, Subhash Nunna wrote:

> def skip_elements(elements):
>               # Initialize variables
>               new_list = []
>               i = 0

You don't need to initialize i since it is populated by enumerate below.

> 
>               # Iterate through the list
>               for i,element in enumerate(elements):
>                            # Does this element belong in the resulting list?
>                            if elements.index(element)%2==0:

You don't need to find the index since you already got i from enumerate.
i is the index. So the above line should just be:

	if i%2 == 0:

>                                          # Add this element to the resulting list
>                                          new_list.append(element)
>                            # Increment i
>                            i += 1

And you don't need to increment i since enumerate() will overwrite it
with the next index anyway.


-- 
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