Previously, when we looked at how you can work with list in Python, we looked some operators and functions. However, a list is a bit more complex, than a normal variable – as you might have already guessed, and not just because you can store more than one value in it.
Python also allows you to use built in functions, or technically methods, with a list because it is an object. (We’ll learn more about classes and objects in a little bit.)
.append() method
The append method lets you add an element to the end of a list.
Remember how we said you couldn’t concatenate a non list item to a list, well append lets you solve that issue.
names = ["Chris","Heather","Tim","Deborah"]
print(names)
names.append("Daniel")
print(names)
Appending is always done at the end of the list.
What is nice, is you can create an empty list, and add items. For example, from user input.
security_questions = []
temp = input("What was your first pet's name? ")
security_questions.append(temp)
security_questions.append(input("What was the first street you lived on?"))
print(security_questions)
.index() method
Do you want to know if an element is in a list? Then you can use the index() function.
However, this should be put in a try/except block since if Python cannot find the list, it will return a ValueError exception. This is unfortunate given that many other languages will error out a little nicer, either with a False Boolean value, or a null value which you can check for in an if statement.
presidents = ["Washington", "Jefferson", "Roosevelt", "Lincoln"]
check = input("Name a president on Mount Rushmore: ")
try :
index = presidents.index(check)
print("That is the", index, "president on Mount Rushmore.")
except ValueError:
print("Your answer of", check,"was not on Mount Rushmore.")
.insert() method
The insert() method is used to insert an element into a specific position in the list. This is different from append() which only adds to the end of a list.
songs = ["Hey Jude", "Yesterday", "Here Comes the Sun"]
print(songs)
songs.insert(0, "Help!")
songs.insert(3, "Come together")
print(songs)
Notice that the index where you want to insert it, is put first, and then the item you are inserting.
.sort() method
If you have a list of elements, you can always use the sort method to arrange them.
Doing so will sort the elements in ascending order (lowest to highest).
songs = ["Hey Jude", "Yesterday", "Here Comes the Sun"]
songs.sort()
print(songs)
# prints - ['Here Comes the Sun', 'Hey Jude', 'Yesterday']
list1 = [2,4,6,8]
list2 = [1,3,5,7]
list1 += list2
list1.sort()
print(list1)
#prints - [1, 2, 3, 4, 5, 6, 7, 8]
Curious about what happens if you have mixed data types?
my_list = [2,-4,"Hey Jude", "Yesterday", "Here Comes the Sun",16,8]
my_list.sort()
# TypeError...
This is because the sort cannot swap between numeric and string data.
.reverse() method
The reverse method will reverse all of the elements in your list.
If you need to sort your list in descending order however, you can run sort() then reverse() as it will reverse the current order of elements in your list.
.remove() method
The remove method will remove an element from your list based upon the value of the element, not the index.
If it cannot find the element, it will throw a ValueError which can be caught in a try/except block set.
songs = ["Hey Jude", "Yesterday", "Here Comes the Sun"]
print(songs)
songs.remove("Yesterday")
print(songs)
songs.remove("Let it Be")
# ValueError
Python’s Built in List Functions was originally found on Access 2 Learn