0
enter numbers in a list and then store only first and last number...so tell where my code is going wrong because my code is storing fisrt and second last number
code:- list1=[] a=input("how mNy numbers u want to store") i=0 while i<a: b=input() list1.insert(i,b) i=i+1 q=1 l=a-1 while q<l: list1.pop(q) q=q+1 for w in list1: print w
15 Answers
+ 2
Why don't you do something like:
array = [ 42, 0, 'test', 256, 'whatever' ]
bound = ( array[0], array[-1] )
print(bound)
... instead of iterating over your list to delete all not boundaries items?
+ 1
here I wrote program for you.
check it out
https://code.sololearn.com/cttMQ2eU6F7Y/?ref=app
+ 1
list1=[]
a=int(input("how mNy numbers u want to store\n"))
i=0
while i<a:
b=input()
list1.insert(i,b)
i=i+1
q=1
l=a-1
while q<l:
list1.pop(-2)
q=q+1
for w in list1:
print(w)
This work. (I tried with 3 1 2 3 and 7 1 2 3 4 5 6 7 and had respectively 1 3 and 1 7) There was an index out of bound exception because when you pop, you change the size of the list so you should either pop -2 (second last) or 1 (second).
I think you tried with 4 values and that is why you obtained the first and second last.
1 2 3 4 -> you pop the value at the index 1 -> 1 3 4 -> you pop the value at the index 2 -> 1 3
0
you forgot to cast a from string to int
0
please point out my mistake ...in which line i am coding wrong...
0
replace a=input... by a=int(input...) and it should work
0
still i am not getting right answer....btw thanks for helping me
0
strange, I did it on the sololearn IDE and it worked ..
0
yes it is displaying first number of list and second last number of list but i want it should display first and last number of list ...and if i am increasing the capacity of list more than 5 then it is displaying pop index out of range
0
thank you to both of you sir for helping me
0
my pleasure :)
0
@visph even if it is not useful in itself, it can be a good exercise to begin to learn about lists :)
0
i relay don't get this question can some one help me
0
@javon question is insert n number in a list and then pop all other numbers from list and store only first and last element of first list.
check my code link to understand it better.
- 1
chou