Today we’ll be going over a few more python functions that we weren’t ready for in out first functions lesson. If you haven’t seen the lesson on arrays and lists, some of this might go over you head.
Ok, so today we’ll be looking at the split(), len(), append() functions. We’ll do the simplest one first, the len() function.
len() – The Length Function
The len() function simply returns the length of the string or list (array) you pass to it. For example if we had a list containing four strings, the len() function would return the integer 4.
- list = [‘These’, ‘Are’, ‘Four’, ‘Strings’]
- x = len(list)
The len() function is really useful for keeping track of lists that don’t always stay the same length. It can be used to end loops and avoid putting in indexes that don’t refer to existing list items. What I mean is if your list has three things, [‘like’, ‘this’, ‘one’], and you attempted to access a fictional fourth item.
split() – The Split Function
The split() function is used to turn strings into lists. There are a few reasons you might want to do this. Perhaps the string is too big to be useful and you only need a few parts of it. Or maybe you want to split someone’s name into their first and last name. That’s actually a good use of it so let me demo some code for you that does just that.
- name = ‘Barack Obama’
- firstLast = name.split(‘ ‘)
- first_name = firstLast
- last_name = firstLast
The output of the function will look like this
- Barack Obama
append() – The Append Function
The append() function is used to add on to the end of a list. For example if I had a list containing three objects and I wanted to add a fourth, it would look something like this.
- list = [‘Object 1’, ‘Object 2’, ‘Object 3’]
- list.append(‘Object 4’)
The new list would now contain all four objects. This is really useful for adding things when using a loop. The length of the list will grow with each passing iteration and therefore act as a counter.