Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Lists
A list is an ordered set of values, where each value is identified by an index.
The values that make up a list are called its elements.
Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can
have any type.
Lists and strings and other things that behave like ordered sets are called sequences.
Python lists can contain:
numbers
strings
numbers and strings
numbers, strings and functions
numbers, strings, functions and lists
The empty list
An empty list is often used to initialize a list:
>>> fillMe = []
Like numeric 0 values and the empty string, the empty list is false in a boolean expression:
>>> if fillMe:
# can also write if []:
...
print 'This is true.'
... else:
...
print 'This is false.'
...
This is false.
Example of different types of lists
A list of numbers:
>>> xlist = [1, 2, 3, 4]
Strings:
>>> ylist = ['a', 'b', 'c', 'd']
Numbers and strings:
>>> comboList1 = [1, 2, 'd', 'e']
Numbers, strings and functions:
>>> # Need to define a function first if it is to be contained in a
list
>>> def sumCart(item1, item2):
...
totalCost = item1 + item2
...
print totalCost
...
>>> zlist = [1, 4, 'a', 'wassup?', sumCart]
Generating a list
Using a while loop
>>>
>>>
>>>
...
...
...
...
...
[4]
[4,
[4,
nums = list()
i = 4
while (i < 9):
nums.append(i)
i = i + 2
print nums
6]
6, 8]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]