#!/usr/bin/env python # coding: utf-8 # # Module 2 # # ## Video 6: Lists and List Operations # **Python for the Energy Industry** # # ## Lists # # We often want to keep track of many bits of data at once. One way of doing this in python is with a 'list'. Lists are defined by enclosing multiple comma-separated values inside square brackets. # In[1]: # list of strings vessels = ['ABIOLA', 'ACACIA'] # list of floats prices = [1.23, 1.98, 1.45, 1.67] # lists of integers quantities1 = [18, 22, 21, 32] quantities2 = [12, 11, 16, 18] # ### Looping Over Lists # In[2]: # loop over prices for price in prices: print(price) # ### List Indexing # # We can access individual items in a list in the following way: # In[3]: prices = [1.23, 1.98, 1.45, 1.67, 2.40, 1.89] print('The 1st price: ', prices[0] ) print('The 2nd price: ', prices[1] ) print('The 3rd price: ', prices[2] ) # The number inside the square brackets is the 'index' of the item. Note that Python uses 'zero indexing', so the first item in a list has an index of 0. # # You can also access items 'from the end' using a negative index. So an index of -1 gives the last item, -2 gives the second last item, and so on. # In[4]: print('The last price: ', prices[-1] ) print('The 2nd last price: ', prices[-2] ) # The index can also be used to overwrite an item in the list: # In[5]: print(prices) prices[0] = 2.41 prices[-1] = 0.99 print(prices) # You can also get a range of items from a list: # In[6]: print(prices[1:4] ) # This is called a 'slice'. Which indices from the prices list are included in this slice? # ## List Operations # # Lists have some built in functionality that makes them easier to work with. # # ### Adding to / Removing from Lists # In[7]: countries = ['USA', 'UK', 'France', 'Germany'] # adding on to the end of a list countries.append('Spain') print(countries) # In[8]: # inserting into a specific index of a list countries.insert(2, 'Australia') print(countries) # In[9]: # removing from a specific index countries.pop(3) print(countries) # In[10]: # removing a particular value from a list countries.remove('Germany') print(countries) # ## Examining Lists # In[11]: primes = [2,3,5,7,11,13] # check if a value is in a list print(3 in primes) print(4 in primes) # In[12]: # find the index of a value in a list print(primes.index(5)) # In[13]: # find the minimum, maximum, and sum print('minimum:', min(primes)) print('maximum:', max(primes)) print('sum:', sum(primes)) # ### Other List Operations # # The addition and multiplication operators also work on lists: # In[14]: print(quantities1 + quantities2) print(quantities1 * 2) # ### Exercise # # Python allows you to have lists containing multiple different types of variable, as in the below example. Try to transform this list into: [1,2,3] using the operations you've learned. # In[ ]: