[Solved] – Python-How to remove the first Item from a list?

How to remove the first Item from a list?

Asked on October 16, 2018 in Python.
Add Comment


  • 5 Answer(s)

    Python List
    list.pop(index)

    >>> l =['a','b','c','d']
    l.pop(0)
    'a'
    l
    ['b','c','d']

    del list[index]

    >>> l =['a','b','c','d']
    dell[0]
    l
    ['b','c','d']

    These together modify your innovative list.
    Others takerecommended using slicing:
    • Duplicates the list
    • Can reoccurrence a subset

    from collections import deque
    l =deque(['a','b','c','d'])
    l.popleft()
    'a'
    l
    deque(['b','c','d'])

    • Carriessophisticated performance cracking from left end of the list

    Answered on October 16, 2018.
    Add Comment

    Sharing:

    x = [0,1,2,3,4]
    x = x[1:]

    Which would reallyarrival a subset of the novel but not modify it.

    Answered on October 16, 2018.
    Add Comment
    >>> x = [0, 1, 2, 3, 4]
    x.pop(0)
    0
    Answered on October 16, 2018.
    Add Comment

    obj − This is the object to be removed from the list.

    This method does not return any value but removes the given object from the list.

    Example :

    The following example shows the usage of remove() method.

    #!/usr/bin/python
    aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
    aList.remove('xyz');
    print "List : ", aList
    aList.remove('abc');
    print "List : ", aList
    
    Answered on December 18, 2018.
    Add Comment

    list.pop(index)

    >>> l = ['a', 'b', 'c', 'd']
    >>> l.pop(0)
    'a'
    >>> l
    ['b', 'c', 'd']
    >>> 

    del list[index]

    >>> l = ['a', 'b', 'c', 'd']
    >>> del l[0]
    >>> l
    ['b', 'c', 'd']
    >>> 

    These both modify your original list.

    Others have suggested using slicing:

    • Copies the list
    • Can return a subset

    Also, if you are performing many pop(0), you should look at collections.deque

    from collections import deque
    >>> l = deque(['a', 'b', 'c', 'd'])
    >>> l.popleft()
    'a'
    >>> l
    deque(['b', 'c', 'd'])
    • Provides higher performance popping from left end of the list
    Answered on February 9, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.