write a program to print the last and first element of list with n
element?
Answers
The given code is written in Python.
n=int(input("How many elements for the list? "))
if n==0:
print("Length is zero. Invalid Input.")
else:
print("Enter the elements into the list.")
a=[]
for i in range(n):
a.append(int(input(">> ")))
print("Given List:",a)
print("First Element:",a[0])
print("Last Element:",a[-1])
- The index value of element starts with 0. So, the first element of list 'a' can be accessed by writing - a[0]. Hence, the first element is printed.
- Python supports negative indexing. Index of last element is -1, last second element is -2 and so on. So, the last element of the list 'a' can be accessed by writing - a[-1. Hence, the last element is also printed.
- Hence, the problem is solved.
See the attachment for output.
Answer:
The given code is written in Python.
n=int(input("How many elements for the list? "))
if n==0:
print("Length is zero. Invalid Input.")
else:
print("Enter the elements into the list.")
a=[]
for i in range(n):
a.append(int(input(">> ")))
print("Given List:",a)
print("First Element:",a[0])
print("Last Element:",a[-1])
Explanation:
The index value of element starts with 0. So, the first element of list 'a' can be accessed by writing - a[0]. Hence, the first element is printed.
Python supports negative indexing. Index of last element is -1, last second element is -2 and so on. So, the last element of the list 'a' can be accessed by writing - a[-1. Hence, the last element is also printed.
Hence, the problem is solved.
Plz mark as brainliest..