11/2/2022 0 Comments Slice back of list![]() ![]() Let’s write the function we have created in the previous section but this time using a list comprehension. The list comprehension is a Python construct that provides an alternative to for loops. SLICE BACK OF LIST HOW TOHow to Get Every Other Element of a List Using a List Comprehension You can then call the every_second_element function. 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. The first argument (start) is equal to 1 and the second argument (end) is equal to the length of the list. Now, create a function that uses a for loop and the range function to generate list indexes. To return every second element we have to change the start value to 1. This is similar to what we have seen with the slice operator. The range function also accepts a third argument, the step. So, the values returned include the first argument passed to the range function and don’t include the second argument. You can use a for loop and the range() function to print every second element of a listįirstly, let’s see what the range function returns by casting its output to a list: > list(range(0,5)) How to Print Every Second Element of a List Using the Range Function This time we have started by index 1, remember that the index for lists starts from zero. If we want to start from the second element in the list the syntax becomes the following: > print(countries) That’s why the output prints every other string in the list. 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. When start and end are not specified the entire list is taken into account. The slice operator follows the syntax below (this is actually called extended slice syntax). Conclusion How Do I Show Every Other Element in a Python List?įirstly, let’s create a list of strings… > countries = Ĭool, the slice operator returns every other element starting from the first. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |