Computer Science, asked by karandeep4621, 2 months ago

write a program to print the last and first element of list with n

element?​

Answers

Answered by anindyaadhikari13
1

\texttt{\textsf{\large{\underline{Solution}:}}}

The given c‎ode 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])

\texttt{\textsf{\large{\underline{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.

See the attachment for output.

Attachments:
Answered by Anonymous
1

Answer:

The given c‎ode 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..

Similar questions