Python Program to Print Element at Even Position in List
This article deals with some Python programs that find and prints all elements at even position in list. Here are the list of programs covered in this article:
- Print Elements (Numbers) at Even Position in List
- Print Characters at Even Position in List
Note - Here index number is considered as position.
Print Numbers at Even Position in List
The question is, write a Python program that find and prints all numbers present at even position in a list given by user. Here is its answer:
nums = [] print("Enter 10 Numbers: ") for i in range(10): nums.insert(i, int(input())) print("\nElements at Even Positions: ") for i in range(10): if i%2==0: print(nums[i])
Here is the initial output of this program's sample run:
Now supply the input say 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 as ten numbers, to print all the numbers at even position (index) as shown in the snapshot given below:
Note - The number (1) at 0th also gets printed as number at even position (index). Because 0 is also an even number. An even number is a number that can be divided into two equal parts. We can divide 0 into two equal parts (0 and 0), so 0+0 is equal to 0. Therefore 0 is an even number.
Modified Version of Previous Program
The end used in this program, to skip insertion of an automatic newline using print(). The str() method converts any type of value to a string type.
arr = [] print(end="Enter the Size: ") arrSize = int(input()) print("Enter " +str(arrSize)+ " Numbers: ") for i in range(arrSize): arr.insert(i, int(input())) print(end="\nThe List is: ") for i in range(arrSize): print(end=str(arr[i])+ " ") print(end="\n\nNumbers at Even Position (Index): ") for i in range(arrSize): if i%2==0: print(end=str(arr[i])+ " ") print()
Here is its sample run with user input, 6 as size and 11, 22, 33, 44, 55, 66 as six numbers:
Print Element (Character) at Even Index in List
This is the last program of this article, that find and prints all the elements available at even position in given list. Let's have a look at the program and its sample run to get clear understanding on it.
arr = list() print(end="Enter the Size: ") arrSize = int(input()) print("Enter " +str(arrSize)+ " Elements: ") for i in range(arrSize): arr.insert(i, input()) print(end="\nThe List is: ") for i in range(arrSize): print(end=str(arr[i])+ " ") print(end="\n\nElements at Even Position (Index): ") for i in range(arrSize): if i%2==0: print(end=str(arr[i])+ " ") print()
Here is its sample run with user inputs, 12 as size, c, o, d, e, s, c, r, a c, k, e, r as twelve elements:
« Previous Program Next Program »
Liked this post? Share it!