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.

  1. list = [‘These’, ‘Are’, ‘Four’, ‘Strings’]
  2. x = len(list)
  3. print(x)

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.

  1. name = ‘Barack Obama’
  2. firstLast = name.split(‘ ‘)
  3. first_name = firstLast[0]
  4. last_name = firstLast[1]
  5. print(first_name)
  6. print(last_name)

The output of the function will look like this

  1. Barack Obama
  2. Barack
  3. 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.

  1. list = [‘Object 1’, ‘Object 2’, ‘Object 3’]
  2. 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.

Leave a Reply