[Tutor] modification to a list

Alan Gauld alan.gauld at yahoo.co.uk
Wed Apr 22 11:15:12 EDT 2020


On 22/04/2020 15:44, shubham sinha wrote:

Oh dear. This has so much wrong that I'm not sure where to start.

> def skip_elements(elements):
>     new_list = [ ]
>     i = 0
>     for element in elements:
>         if "element" != "elements(i):

Lets ignore the mismatched sting quote for now since the code
wouldn't run with it there, so it must be a typo for the email...

The line asks if the literal string "element" is different
to the return value of a function called elements which
you call with the value i. But there is no function elements.
So this should give an error too.

Lets assume you meant to use square brackets to access
the list... Then you compare the string "elements" to
each value of the list elements. Since "element" does
not appear anywhere in your input data the test will
always be false so you will append the element to your
new list. That's why you always get all of the elements.

>             new_list.append(element)

I assume what you were trying to write was:

for elemet in elements:
    if element != element[i]:
           new_list.append(element)

>         i += 2

Now things get more complicated because you increment
the index by 2 but your loop is looking at every item
in the list. So your comparison is now with every
second item. Lets draw up a table to see what the
various values are for "abcdefg":

element   i  element[i]
a	0	a
b	2	c
c	4	e
d	6	g
e	8	BANG! Should give an error. Only 6 items

The result should be only the first item will be
ignored all others get added to the list until the
index gets too big. Not at all what you want.

There are in fact multiple easier ways to do this. It depends on how
much you have covered in your course.
If you have looked at slicing you can do it in a single line.
If not you could try something like:

def skip_elements(elements):
    new_list = []
    is_needed = True
    for element in elements:
        if is_needed: new_list.append(element)
        is_needed = not is_needed
    return new_list

Which is a code translation of the requirements.
If you really want to fuss with indexes you could do

def skip_elements(elements):
    new_list = []
    for i in range(len(elements)):
        if i % 2 == 0:
           new_list.append(elements[i])
    return new_list

But that's pretty horrible Python, even if it is shorter.


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