Create a function named
odd_indices() that has one parameter named
The function should create a new empty list and add every element from
lst that has an odd index. The function should then return this new list.
odd_indices([4, 3, 7, 10, 11, -2]) should return the list
[3, 10, -2] .
for index in range(1, len(lst), 2):
Question From me:
Like I always say I like to ask the why, what thought process goes into getting the solution that was given because thats where I run into problems, because my logical thinking hasn’t caught up to my understanding of the knowledge of python. So what’s the thought process and how was this answer came too? thank you
This answer is much simpler than the one I came up with, but much better. Basically, the challenge wants a list with every odd numbered indexed item. So:
Each item has and index. Indexes go like this: 0, 1, 2, 3, 4… Therefore, if I want every odd-numbered index (1, 3, 5…) then I want every second index.
When it says
in range(1, len(lst), 2, it is saying, every number that is between
1 (the first number in the
range() function) and the length of the list (the second number in the
range() function)-remember range is exclusive - it goes up to, but not to the number.Lastly it is saying, only go to every second number (the third and final number in the
range() function. Basically, the program is saying, “for every second number between 1 and the length of the list, add it to a new list.”
The thought process behind solving the problem, as with many code problems, is to do this:
- Visualise the problem in the real world; what would I do if I had it on a piece of paper.
- Write instructions as though you are telling a human to do it(pseudo code).
- Lastly, translate your pseudo code into Python.
I hope this helps!
thank you so much, this really helped me understand