Ask coding questions

← Back to all posts
How to get the values from a list and discluding other values in python
MikeJMS8910 (234)

So I have this list that I made but I was wondering if it is possible to get values from the list but only a certain amount.
Lets say that I have a list that was
list = ['2', '1', '2', '3', '7']
Would there be a way for me to make a variable that has all of the values but gets rid of the first and last one? If there is then how would I be able to do that? It would have to be custom so that I can give the function any list and it does it for me.

Answered by 19ecal (233) [earned 5 cycles]
View Answer
19ecal (233)

This should do it

def removeFirstAndLast(_list): return _list[1:-1]
19ecal (233)

That should work for strings as well

MikeJMS8910 (234)

@19ecal it works thanks but is there a way that I can print it without the comma and the []

19ecal (233)


def removeFirstAndLast(_list):
    shortlist= _list[1:-1]
    for i in shortlist:
        val+=(i+" ")
    return val
MikeJMS8910 (234)

@19ecal can you explain to me a little more about how this works because I need some similar function just not disincluding the first and last

19ecal (233)

@MikeJMS8910 So, to get specific elements of a list, you can use square brackets ([])

_list=[1, 2, 3, 4, 5]
#Output the first element
#Remember list indices start at 0

To get the elements from position x (inclusive) to position y (exclusive), you can do
_list[x:y] (note the colon)
Also, the last element in a list is at index -1 and therefore the penultimate element is at [-2], continuing down
What I have done, then, is told python to return the list from the second position to the second-last one.
inclusive/exclusive means that the element at position x is included, but the one at position y is not