
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 the 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.
- Related Questions & Answers
- Python – Check alternate peak elements in List
- Alternate range slicing in list (Python)
- Alternate element summation in list (Python)
- Product of the alternate nodes of linked list
- Accessing all elements at given Python list of indexes
- Python - Increasing alternate element pattern in list
- Find all elements count in list in Python
- Python – Rows with all List elements
- Count occurrence of all elements of list in a tuple in Python
- Increasing alternate element pattern in list in Python
- Sum of the alternate nodes of linked list in C++
- Alternate sorting of Linked list in C++
- Check if list contains all unique elements in Python
- Removing all the elements from the List in C#
- Python - List Initialization with alternate 0s and 1s
Advertisements