Python Python Collections Slices Slice Functions

Phillip Bailey
Phillip Bailey
1,746 Points

Printing odd values. Close but not really.

This is what I have so far, but I understand i'm not using slices. I feel like maybe I'm making this harder than it should be. I thought it would be cool to iterate through and return od indexes by comparing the current index being divisible by 2 or not. I was getting erros about not all things were converted etc. And, since if I use a string, I cant do math on a sting I think, thats why I should retry this with slices only. Any advice would be helpful just to see how I could use this for loop in a similar approach.

def odds(word): for odd in word: if (odd % 2) >0: print(odd) return(odd)

list_1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] odds(list_1)

slices.py
def first_4(iterable):
    return iterable[0:4]

def first_and_last_4(iterable):
    #first_4 = iterable[0:4]
    return iterable[0:4] + iterable[-4:]

def odds(word):
    for odd in word:
        if (odd % 2) >0:
            print(odd)
    return(odd)

list_1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
odds(list_1)

1 Answer

Steven Parker
Steven Parker
163,023 Points

Your idea is sound, but needs a bit more work. Doing this with slices is a whole lot easier, and is the point of this challenge. You should really try to do it with a slice.

But just so you'll know what went wrong:

  • you need to test the index, not the item itself
  • you'd probably need the "enumerate" function to get the indexes with the items
  • you need to return a new list containing all the odd-indexed items (not just one of them)
  • you don't need to "print" anything
Phillip Bailey
Phillip Bailey
1,746 Points

Okay, I have not seen the enumerate function yet. I tried this and it work in IDLE but still wrong answer with slices. def

odds(the_iterable): return the_iterable[::2] when I put a list through it, seems to work and if I put a string it works but im still a little lost.

Steven Parker
Steven Parker
163,023 Points

You're really close, the step of 2 was a good idea. But the index numbers start with 0, which means you would be returning the evens instead of the odds. So give your slice a start value so you get the odds instead.