Algorithms: Uog - Edu.gy
Algorithms: Uog - Edu.gy
uog.edu.gy |
LIST
>>> myList = [42, 'cat', 3.142]
>>> myList
>>> len(myList)
>>> myList[1]
'cat'
>>> myList.append(269)
>>> myList
>>> myList
42
>>> myList
>>> myList.pop()
269
>>> myList
['dog', 3.142]
You may have noticed that two different mechanisms are at work in these examples. Some of the things
we can do with lists involve functions . For instance
len(myList)
>>> aList
Note that lists can contain multiple copies of the same item.
>>> aList
A very useful operation is called slicing . The next examples illustrate its use.
Notice that if a list is too long to fit on one line we can just press Enter and then continue the list on the
following line.
>>> aList[2:4]
['cicada', 'dragonfly']
>>> aList[3:]
>>> # slice from the beginning of the list up to but not including index 2
>>> aList[:2]
['ant', 'bee']
>>> aList
Lists in Python can grow or shrink as items are added or removed. It’s very common to start with an
empty list and add items to it.
>>> list2 = []
>>> list2.append(2)
>>> list2.append(7)
>>> list2.append(1)
>>> list2.append(8)
>>> list2
[2, 7, 1, 8]