If you want to iterate through a list from a second item, just use Show
Probaly, a part of your function just lost somewhere, but anyway, in in general range() works like this:
i. e.
Edit Please, remember: python uses zero indexing, i.e. first element has an index 0, the second - 1 etc. By default,
Detailed description of Getting every other element from a Python list might seem easy to do but it actually requires some knowledge of Python basics. To get every other element in a Python list you can use the slice operator and use the fact that this operator allows to provide a step argument (with its extended syntax). Another approach is to use the mathematical concept of remainder and apply it to list indexes. Let’s get creative and come up with multiple ways to solve this problem!
Firstly, let’s create a list of strings…
Cool, the slice operator returns every other element starting from the first. The slice operator follows the syntax below (this is actually called extended slice syntax). string[start:end:step] When start and end are not specified the entire list is taken into account. The step value allows to skip some of the items in the list, in our example we have passed 2 as the value of the step. That’s why the output prints every other string in the list. If we want to start from the second element in the list the syntax becomes the following:
This time we have started by index 1, remember that the index for lists starts from zero. How to Print Every Second Element of a List Using the Range FunctionYou can use a for loop and the range() function to print every second element of a list Firstly, let’s see what the range function returns by casting its output to a list:
So, the values returned include the first argument passed to the range function and don’t include the second argument. The range function also accepts a third argument, the step. This is similar to what we have seen with the slice operator.
To return every second element we have to change the start value to 1.
Now, create a function that uses a for loop and the range function to generate list indexes. The first argument (start) is equal to 1 and the second argument (end) is equal to the length of the list.
We use the list append method to create a new list that only contains every second value, we then return the new list at the end of the function. You can then call the every_second_element function.
How to Get Every Other Element of a List Using a List ComprehensionThe list comprehension is a Python construct that provides an alternative to for loops. Let’s write the function we have created in the previous section but this time using a list comprehension. We will still use the range() function.
When you see a list comprehension for the first time it might seem complex, but it’s actually straightforward when you get used to it. And the big advantage is that it has replaced a function made of multiple lines with a single line of code. Fantastic! Using the Enumerate Function to Get Every Other List Element in PythonAnother way to get every other element from a list is by using the Python enumerate function. The enumerate function returns an enumerate object:
What can we do with this object? You can use an enumerate object to print index and value for each element in a list.
That’s handy because you don’t have to handle the index yourself avoiding potential errors when working with indexes. Use a list comprehension and the enumerate function to print every second element of a list.
If you look at the end of the list comprehension, you can see that we have also used the remainder (Python modulo operator) to print only elements with odd indexes. Extract Every Other Element From a Python List Using a LambdaTo extract every other element from a list we can also use a Python lambda function. When used together with filter() a lambda function allows to filter each element of a list. filter(function, iterable) We can use a lambda function to verify if the reminder for a given index is equal to 1.
Here is how it looks like when applied to the indexes of our list:
Let’s call the filter function and pass the following arguments to it:
Now, use the call to the filter function inside a list comprehension…
The result is the same we have seen in previous sections but the implementation is a lot more complex. Still, this is an opportunity for you to learn how to use a few Python constructs:
How to Get Every nth Element from a Python ListWe will complete this tutorial by looking at how to retrieve every nth element from a Python list. Let’s create a function that takes three arguments:
Now, use the input function to get the values of start index and n from the command line when executing the Python program.
Note: we have used the int() function to convert the strings returned by the input() function into integers. And finally we can call our function:
The two print statements use the string format() method to print two messages when you execute the program. Here are three runs of the program to test it returns the expected result.
All good, the code works fine 🙂 ConclusionWe have seen so many different ways to get every other element in a Python list. You have seen how to use:
The simplest approach is the extended syntax for the slice operator. Which one do you prefer? Related posts:I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer! How do you do two loops in Python?First, Write an outer for loop that will iterate the first list like [for i in first] Next, Write an inner loop that will iterate the second list after the outer loop like [for i in first for j in second] Last, calculate the addition of the outer number and inner number like [i+j for i in first for j in second]
How do I loop a second index in Python?If you want to iterate through a list from a second item, just use range(1, nI) (if nI is the length of the list or so). i. e. Please, remember: python uses zero indexing, i.e. first element has an index 0, the second - 1 etc. By default, range starts from 0 and stops at the value of the passed parameter minus one.
How do you get the second element in a list Python?As we want second to last element in list, use -2 as index.
How do you print every second element in Python?“python get every second element” Code Answer's. # Basic syntax:. new_list = your_list[start_index::spacing]. # Example usage using list slicing:. # Say you have the following list and want every third item.. your_list = [0,1,2,3,4,5,6,7,8,9]. new_list = your_list[0::3]. print(new_list). |