0

The following is my code:

data = raw_input("Please enter your particulars in the format of name/age/address ->")

pro = data.split("/")

name = pro.pop(0)
age = pro.pop(1)
address = pro.pop()

print name
print age
print address

I understand that the index of a list goes by 0, 1, 2 but when i pop the age (which should be index 1 in the list), it gives me the address when it is printed. Likewise for the address it gives me the age instead. Can someone tell me what in the world is wrong with this thing?

4
  • 2
    pop() is completely unnecessary... Commented Jun 11, 2015 at 12:37
  • You pro list shrinks after pop(0), so in the next pop operation you only have 2 elements i.e age and address so pop(1) gives you address and like wise. Commented Jun 11, 2015 at 12:37
  • 4
    This seems complicated. Consider doing name, age, address = data.split("/") and then you don't have to worry about indices at all. Commented Jun 11, 2015 at 12:39
  • Looking at the value of pro after each pop operation would have given you some idea of what was going on. Commented Jun 11, 2015 at 12:43

3 Answers 3

6

Its because when you already pop index 0, other items shift left by 1 and so the index 1 moves at 0.

So you must do -

name = pro[0]
age = pro[1]
address = pro[2]
Sign up to request clarification or add additional context in comments.

Comments

3

Originally, the list is like this:

name  age  address
# 0    1      2

age is at index 1. However, after you pop out name, it's

age address
# 0    1

age is now at index 0.

Comments

0

As mentioned, pop() is completely unnecessary. However, it's important to understand what's happening when you were using it.

Calling pop() removes and returns an item from a list, at a given index. So, once the first item (at index 0) is popped, the new first item is the next item you're after (the item that was at index 1).

If you absolutely want to use pop(), the following works (but isn't recommended):

>>> name = pro.pop(0)
>>> age = pro.pop(0)
>>> address = pro.pop(0)

If you were then to print pro, you'd see the following:

>>> print pro
[]

Yep, an empty list (that has had all elements "popped" off).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.