Lists
Contents
Lists#
Programming for Geoscientists Data Science and Machine Learning for Geoscientists
A list is an object that contains multiple elements in defined order (called an index number). The syntax is:
l = [element0, element1, element2, element3, ...]
Note that indexing in python starts at 0! To extract a specific element or part of the list, we can use slicing syntax:
l = [1, 3, 5, 9, 7, 11]
# Print first element (index 0!)
print(l[0])
# Print elements three to six (not inclusive), returns a list
print(l[2:6])
# Print every second element but the last two excluded
print(l[:-3:2])
# Print what class l is
print(type(l))
1
[5, 9, 7, 11]
[1, 5]
<class 'list'>
The same operations can be done to lists of strings:
shopping_list = ["potatoes", "cucumber", "apples",
"bananas", "milk", "juice"]
# Print first element
print(shopping_list[0])
# Print elements three to six, returns a lis
print(shopping_list[2:6])
# Print every other elements but the last two excluded
print(shopping_list[0:-3:2])
# Returns class list
print(type(shopping_list))
potatoes
['apples', 'bananas', 'milk', 'juice']
['potatoes', 'apples']
<class 'list'>
Other operations on lists:
l = [1, 3, 5, 9, 7, 11]
print(len(l)) # Prints the number of elements in the list
l.append(13) # Appends 13 at the end of the list
print(l)
print(min(l)) # Returns minimum value in the list
print(max(l)) # Returns maximum value in the list
print(sum(l)) # Sums up elements of the list
l = l + [17, 19] # Adds a list [17, 19] at the end of l
print(l)
l.insert(2, 305) # Insert at index 2, number 305
print(l)
del l[2] # Delete the element we inserted at index 2
print(l)
print(l.index(11)) # Return what index value 11 has
print(305 in l) # Check if 305 is in the list
6
[1, 3, 5, 9, 7, 11, 13]
1
13
49
[1, 3, 5, 9, 7, 11, 13, 17, 19]
[1, 3, 305, 5, 9, 7, 11, 13, 17, 19]
[1, 3, 5, 9, 7, 11, 13, 17, 19]
5
False
Exercises#
Multi-type lists compared to other programming languages Python is very flexible when it comes to types of objects inside them. For example, we can have the following list:
l = [1,"0",True]
Try to transform the above list into the following one using list operations such as
del
andappend
:l = [1,2,3]
Print the largest element of the list.
Answer
l = [1,"0",True]
del l[2]
del l[1]
l.append(2)
l.append(3)
print(l)
print(max(l))