
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
List Consisting of All Alternate Elements in Python
In this article, we are going to learn how to get alternate elements from the list. We'll see two different ways to solve the problem.
Follow the below steps to solve the problem in one way.
- Initialize the list.
- 3Iterate over the list and store all the elements from the odd index.
- Print the result.
Example
Let's see the code.
# Initializing the list numbers = [1, 2, 3, 4, 5] # finding alternate elements result = [numbers[i] for i in range(len(numbers)) if i % 2 != 0] # printing the result print(result)
If you run the above code, then you will get the following result.
[2, 4]
We'll get all the odd positioned elements using slicing. Follow the below steps to solve the problem.
- Initialize the list.
- Get element which are in odd index using [1::2] slicing.
- Print the result.
Example
Let's see the code.
# Initializing the list numbers = [1, 2, 3, 4, 5] # finding alternate elements result = numbers[1::2] # printing the result print(result)
If you run the above code, then you will get the following result.
Output
[2, 4]
Conclusion
If you have any queries in the article, mention them in the comment section.
Advertisements