Building lists

Steven D'Aprano steve+comp.lang.python at
Tue Oct 21 01:55:08 CEST 2014

Seymore4Head wrote:

> For starters I would like to know if you can make a single item list
> and then turn it into a 2 item list.  Is there a command for that?
> Do you have to know the number of items the list will have before
> making it?

Now these are the right sort of questions that you should be asking!

They are concrete and tightly focused, not vague and so broad that they
could mean anything, and they invite a concrete answer rather than hints.

First question: can you take a single list item and turn it into a 2-item
list? Yes, you can, you can turn a single list item into *anything*,
including deleting it. Start with a list, and remember that lists are
indexed starting with 0:

py> alist = [1, 2, 4, 8, 16, 32, 64]
py> alist[0] = "hello!"
py> alist[1] = ["a", "b", "c"]
py> del alist[4]
py> print(alist)
['hello!', ['a', 'b', 'c'], 4, 8, 32, 64]

Second question: do you need to know the number of items in a list in
advance? No. You can add additional items to an existing list with the
append() method:

py> import random
py> alist = []
py> while random.random() < 0.5:
...     alist.append("spam")
py> print(alist)
['spam', 'spam']

Because this is random, if you try it you will get an unpredictable number
of "spam" words in the list. About half the time it will contain no words
at all, about a quarter of the time it will contain a single word, an
eighth of the time it will contain two words, and so forth.


More information about the Python-list mailing list