Py-Tut-004

Back to Learning Python

Lists
A List is a collection of objects. In previous examples, a Variable was used to represent a single item of a single type (integer, string, etc.). A List is used when you want to be able to represent multiple items of any type. Lists have similarities to Arrays but Arrays are not included by default in Python so we will focus on Lists for now.

To create a list, enclose the items with square brackets [] and separate with a comma. code format="python" myList = [ 2, "Eric Idle", 6*7 ] code

To print the entire list: code format="python" print myList code

Indexing
To reference a specific item, you use the list name and square brackets of the item you want. However, referencing specific items in a list may be different than you expect. Indexing is zero-based which means that the first item is always zero and the nth item is always n minus one. For example, to reference each item from the list above:

code format="python" print print 'Each item of my list myList is:', myList[0], ',', myList[1], ',', myList[2] code

For the three items above the index values were 0, 1, 2. Notice as well that we manually put commas ',' between each item to display them all easier.

Assignment 4
Write a program that asks the user for three items. Print the entire list then print each item on a separate line.

Back to Learning Python