1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Rep Power

    Cannot explain output of list after popping

    Hi people! I just started learning python, and my question might seem stupid for some of you, so please bare with me.

    I am trying to pop an element from a list, and output the elements of the list, but I cannot explain the output.

    Here goes the code

    list1 = [1,2,3,4,5,6]
    print "list1 before pop(1) is "
    print list1
    print "list1 after pop(1) is "
    print list1
    print "list1[1:3] is "
    print list1[1:3]
    print "list1[1] is "
    print list1[1]
    print "list1[2] is "
    print list1[2]
    print "list1[3] is "
    print list1[3]

    And here is the output of the code

    list1 before pop(1) is
    [1, 2, 3, 4, 5, 6]
    list1 after pop(1) is
    [1, 3, 4, 5, 6]
    list1[1:3] is
    [3, 4]
    list1[1] is
    list1[2] is
    list1[3] is

    Can someone explain to me why list1[1:3] is [3, 4] and not [3, 4,5] ?

    Thanks guys.
  2. #2
  3. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Rep Power
    OK, so i admit the only part of your post I read was
    list1[1:3] is [3, 4] and not [3, 4,5] ?

    slices are closed intervals on the left, open intervals on the right.

    The slice [1:3] are indicates the indexes 1 and 2.

    Imagine a loaf of sliced bread. Number the slices sequentially from 0 to 21. For the slice [1:3] put a spatula between bread objects 0 and 1, and put another spatula between the bread objects labeled 2 and 3. Pinch the spatulas and lift out the bread. You'll get objects 1 and 2.

    Spend some time with the interpreter. Explain the outcome of these experiments:

    print(list(range(2, 8)))


    print(list(range(3, 10, 2)))

    print(list(range(4, 10, 2)))

    And if all this fails you, spend some time with the python tutorial at docs.python.org

    Get it? I guessed your misunderstanding because you expected 3 items while unless you did something really strange I expected 2 objects.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Rep Power
    oh ok, I get it! Thanks!

IMN logo majestic logo threadwatch logo seochat tools logo