0

According to the docs:

list.append(x): Add an item to the end of the list

So, if I do:

list = []
list.append("banana")
print list[0] --> which is suppose to print the FIRST item of the list
> banana

So far so good, however if now I append another item:

list.append("apple")
print list[0]

apple

Wasn't it suppose to append to the END of the list? How do I keep the order of the list when appending? How should I print the first and last items of the list -- in the order they were added to it?

Thanks

4
  • 4
    You shouldn't use the name list as a variable name. However, you must be missing something in your question. Append add's elements to the back of the list Commented Mar 23, 2011 at 19:47
  • Just out of curiosity, you're not actually using the variable name list in your code, correct? Big no-no Commented Mar 23, 2011 at 19:47
  • @S.Lott, my reasoning was to provide an alert to other users who could be trying to answer the question as I still needed 10 minutes to accept the answer. Commented Mar 23, 2011 at 20:05
  • Folks are going to answer anyway. Even after you accept an answer. Not to worry about them. You got what you needed, that's what mattered. Commented Mar 23, 2011 at 20:23

2 Answers 2

3
>>> l = []
>>> l.append('banana')
>>> print l[0]
banana
>>> l.append('apple')
>>> print l[0]
banana
>>> print l
['banana', 'apple']

Works fine for me, are you sure you aren't clearing the list anytime?

Sign up to request clarification or add additional context in comments.

1 Comment

Ahn! You nailed it! It is recreating the list on a loop! Thanks, I was getting nuts with it.
1

Works for me. You probably ought to pick a name other than list, since there's a built-in function called list.

>>> list = []
>>> lst = []
>>> lst.append("banana")
>>> print lst[0]
banana
>>> lst.append("apple")
>>> print lst[0]
banana
>>> print lst
['banana', 'apple']

2 Comments

it works even with "list" for me. BTW.. you can ommit the "print"
@Bastian: I know it works, but it's a bad idea. And I was trying to change as little as possible from the OP's example, but yes, print can be omitted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.