0

Write a program that takes a list as input and outputs the last element of that list. The input list can be of any size

I'm getting a hard time getting this lol probably easy solution

28th Apr 2021, 11:15 PM
O'vonee Delpesche
O'vonee Delpesche - avatar
9 odpowiedzi
+ 5
I am surprised... I wrote this code: x = list(input()) lastelement = x[-1] print(lastelement) But for test case 2, the input is 42 (only element) and my output is 2. All other test cases no problem. What could be wrong?
14th Jun 2021, 3:23 PM
João Guerreiro
João Guerreiro - avatar
+ 5
x = input() elements = x.split() #your code goes here print(x[-2]) print(x[-1])
30th Jun 2021, 4:26 PM
Lokendra Gupta
Lokendra Gupta - avatar
+ 2
str = input() print(str[-1])
31st Mar 2022, 9:44 PM
Abdelkhalek Nael Ahmad Allan
Abdelkhalek Nael Ahmad Allan - avatar
+ 1
Share your attempt at the solution. Give an example of the input, as a list could be input in may forms (I.E. space separated, comma separated, no separation, etc) The last element can always be found using -1 as the index.
28th Apr 2021, 11:26 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Try this: print(elements[-1])
23rd Aug 2023, 3:35 PM
Mehdi Sadeghi
0
Its very easy, U can get list from the user by using "eval" & use -1 index for getting last element from the list:- L= eval(input ("Enter the list in comma separated form in [ ] : ")) LastEle= L[-1] print(LastEle)
29th Apr 2021, 12:43 AM
Priyanshu Kumar
Priyanshu Kumar - avatar
0
Approach 1: Using map() x=list(map(int,input.split())) print(x[-1]) Approach 2: list comprehension x=int(input()) lis_t=[input() for i in range(x)] print(lis_t[-1]) Approach 3: Using Normal for loop, x=int(input()) lis_t=[] for i in range(x): lis_t.append(input()) print(lis_t[-1])
29th Apr 2021, 2:21 AM
Rahul Saxena
Rahul Saxena - avatar
0
# Asks input from user separated by commas user_string = input("Enter items separated with \",\": ") # stores the comma separated values in a list named user_list user_list = user_string.split(",") print() #an empty line for vis print() #an empty line for vis # prints user_list for visual purposes print("User_list = ", user_list) print() #an empty line for vis # prints the last item in user_list print("The last item is,", user_list[-1])
4th Mar 2022, 9:51 PM
Matumbai Binale
Matumbai Binale - avatar
0
x = input() elements = x.split() #your code goes here print(elements[-1])
26th Mar 2022, 8:08 PM
WALBERTO