0

I have written a function in Python which includes a loop and some conditional statements. I would like to know how I can simplify the code.

The program is supposed to do the following:

Write a function called "middle" that takes a list and returns a new list that contains all but the first and last elements.

I am using an "if" statement and three "elif" statements where two of these "elif" statements have two lines of code repeated. The program works perfectly. But, I have a sense that it can be written in a more professional (i.e., elegant and shorter) way.

def middle():
    i=0
    list=[]   #an empty list
    while True:
        entry=input("Enter the list memeber:  ")
        if entry !="done":
            list.append(entry)
            i=i+1
        elif i==0:
            print("Your list is empty :(!")
            exit()
        elif i==1:
            del list[0]
            print("The remaining list is:  ", list)
            exit()
        elif i>=2:
            del list[0]
            del list[-1]
            print("The remaining list is:  ", list)
            exit()
middle()

3 Answers3

0

You can use list slicing, for example:

if len(array) > 1:
    array = array[1:-1]
    print("Remaining list is :", array)

else:
    print("Your list is too small")
MoonMist
  • 1,232
  • 6
  • 22
0

You can slice the list:

def middle(sample_list):
    sample_list = sample_list[1:-1] # Starting from the second element until one before the last
    print(sample_list) # Print out the list
    return sample_list
middle([5,6,4,3,1]) # Call middle with list as an argument

Output:

[6, 4, 3]

Here is an excellent post on slicing and slice notation to help you understand it further.

GKE
  • 960
  • 8
  • 21
  • This function does not return a `list`. – juanpa.arrivillaga Feb 01 '19 at 00:50
  • @juanpa.arrivillaga Edited, thanks for letting me know! – GKE Feb 01 '19 at 00:53
  • So, slicing of the first and the last element works irrespective of the length of the list. But, poping a list element requires a specific position of the elements. – Navid Asgari Feb 01 '19 at 01:24
  • @Navid Popping a list element does not require a specific position of the elements if you're using data structure types such as Queues, Stacks, deques, any FIFO or LIFO data structure. – GKE Feb 01 '19 at 02:06
0

you can solve it by

a=[1,2,3,4,5]

b=a[1:-1]

print(b)