3.1.4.14 SECTION SUMMARY
Key takeaways
1. The list is a type of data in Python used to store multiple objects. It is an ordered and mutable collection of comma-separated items between square brackets, e.g.:
myList = [1, None, True, "I am a string", 256, 0]
2. Lists can be indexed and updated, e.g.:
myList = [1, None, True, 'I am a string', 256, 0]
print(myList[3]) # outputs: I am a string
print(myList[-1]) # outputs: 0
myList[1] = '?'
print(myList) # outputs: [1, '?', True, 'I am a string', 256, 0]
myList.insert(0, "first")
myList.append("last")
print(myList) # outputs: ['first', 1, '?', True, 'I am a string', 256, 0, 'last']
3. Lists can be nested, e.g.:
myList = [1, 'a', ["list", 64, [0, 1], False]]
.
You will learn more about nesting in module 3.1.7 - for the time being, we just want you to be aware that something like this is possible, too.
4. List elements and lists can be deleted, e.g.:
myList = [1, 2, 3, 4]
del myList[2]
print(myList) # outputs: [1, 2, 4]
del myList # deletes the whole list
Again, you will learn more about this in module 3.1.6 - don't worry. For the time being just try to experiment with the above code and check how changing it affects the output.
5. Lists can be iterated through using the
for
loop, e.g.:myList = ["white", "purple", "blue", "yellow", "green"]
for color in myList:
print(color)
6. The
len()
function may be used to check the list's length, e.g.:myList = ["white", "purple", "blue", "yellow", "green"]
print(len(myList)) # outputs 5
del myList[2]
print(len(myList)) # outputs 4
7. A typical function invocation looks as follows:
result = function(arg)
, while a typical method invocation looks like this:result = data.method(arg)
.
Exercise 1
What is the output of the following snippet?
lst = [1, 2, 3, 4, 5]
lst.insert(1, 6)
del lst[0]
lst.append(1)
print(lst)
Exercise 2
What is the output of the following snippet?
lst = [1, 2, 3, 4, 5]
lst2 = []
add = 0
for number in lst:
add += number
lst2.append(add)
print(lst2)
Exercise 3
What happens when you run the following snippet?
lst = []
del lst
print(lst)
Exercise 4
What is the output of the following snippet?
lst = [1, [2, 3], 4]
print(lst[1])
print(len(lst))
Comments
Post a Comment