Write a Python Program to print Elements in a List with a practical example.
The print function automatically prints elements in a List.
a = [10, 50, 60, 80, 20, 15]
print("Element in this List are : ")
print(a)
Element in this List are :
[10, 50, 60, 80, 20, 15]
Python Program to print Elements in a List Example
This python program is the same as above. But this time, we are using For Loop to iterate every element in a list, and printing that element. This approach is very useful to alter the individual item using this Python index position.
a = [10, 50, 60, 80, 20, 15]
print("Element in this List are : ")
for i in range(len(a)):
print("Element at Position %d = %d" %(i, a[i]))
Element in this List are :
Element at Position 0 = 10
Element at Position 1 = 50
Element at Position 2 = 60
Element at Position 3 = 80
Element at Position 4 = 20
Element at Position 5 = 15
The print function also prints the string elements in a List.
Fruits = ['Apple', 'Orange', 'Grape', 'Banana']
print("Element in this List are : ")
print(Fruits)
Printing the list items outputs as shown below.
Element in this List are :
['Apple', 'Orange', 'Grape', 'Banana']
This list items program is the same as above. But, we used For Loop to iterate each string element in a list.
Fruits = ['Apple', 'Orange', 'Grape', 'Banana']
print("Element in this List are : ")
for fruit in Fruits:
print(fruit)
Element in this List are :
Apple
Orange
Grape
Banana
This Python program allows users to enter any integer value, and it is the length of a List. Next, we used For Loop to add numbers to the list.
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
for i in range(Number):
print("The Element at index position %d = %d " %(i, NumList[i]))