Empty List

Steven D'Aprano steve at pearwood.info
Sun Jun 26 23:48:14 EDT 2016


On Mon, 27 Jun 2016 01:13 pm, Elizabeth Weiss wrote:

> Hi There,
> 
> What is the point of this code?:
> 
> word=[]
> print(word)
> 
> The result is []
> 
> When would I need to use something like this?

As given, never. Nor would you need:

num = 0
print(num)


It's pretty boring, trivial code that does nothing interesting. And you
could simplify it, make it even more trivial:

print([])


Why would you do that? You probably wouldn't bother.

But each line is very useful, if taken as part of a bigger, more useful
program! Look at the first line:

word = []

This creates a variable, "word", and assigns an empty list to it.

But once you have an empty list, you can start putting things into it. Once
you have a list with items in it, there are all sorts of things you can
usefully do:

- append items to the end;
- insert items at the start or the middle;
- sort the list;
- reverse the list;
- pull items out of the list;
- count how many items are in the list;
- search for matching items

and many more. The sky is the limit, and that's what programming is about.
Just because the list *starts* as empty doesn't mean it must remain empty
forever.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list