#!/usr/bin/env python # coding: utf-8 # # Advanced Lists # # In this series of lectures we will be diving a little deeper into all the methods available in a list object. These aren't officially "advanced" features, just methods that you wouldn't typically encounter without some additional exploring. Its pretty likely that you've already encountered some of these yourself! # # Lets begin! # In[1]: l = [1,2,3] # ##append # You will have definitely have use this method by now, which merely appends an element to the end of a list: # In[2]: l.append(4) l # ##count # We discussed this during the methods lectures, but here it is again. count() takes in an element and returns the number of times it occures in your list: # In[4]: l.count(10) # In[5]: l.count(2) # ##extend # Many times people find the difference between extend and append to be unclear. So note: # # **append: Appends object at end** # In[6]: x = [1, 2, 3] x.append([4, 5]) print x # **extend: extends list by appending elements from the iterable** # In[7]: x = [1, 2, 3] x.extend([4, 5]) print x # Note how extend append each element in that iterable. That is the key difference. # ##index # index will return the index of whatever element is placed as an argument. Note: If the the element is not in the list an error is returned. # In[10]: l.index(2) # In[11]: l.index(12) # ##insert # insert takes in two arguments: insert(index,object) This method places the object at the index supplied. For example: # In[12]: l # In[13]: # Place a letter at the index 2 l.insert(2,'inserted') # In[14]: l # ##pop # You most likely have already seen pop(), which allows us to "pop" off the last element of a list. # In[15]: ele = l.pop() # In[16]: l # In[17]: ele # ##remove # The remove() method removes the first occurrence of a value. For example: # In[18]: l # In[19]: l.remove('inserted') # In[20]: l # In[21]: l = [1,2,3,4,3] # In[22]: l.remove(3) # In[23]: l # ##reverse # As you might have guessed, reverse() reverses a list. Note this occurs in place! Meaning it effects your list permanently. # In[24]: l.reverse() # In[25]: l # ##sort # sort will sort your list in place: # In[26]: l # In[27]: l.sort() # In[28]: l # **Great! You should now have an understanding of all the methods available for a list in Python!**