fbpx

List Functions

Append

The append() function allows us to add a new value to the end of a list. For example:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

students.append("Obi-Wan")
students.append("Yoda")

print(students)
# "Luke", "Leia", "Han", "Chewie", "Lando", "Obi-Wan", "Yoda"
				
			

Insert

The insert() function allows us to add a new value to a specified index in a list. In the parentheses, we put the desired index and the value to insert. For example:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

# Add Obi-Wan between Leia and Han:
students.insert(2, "Obi-Wan")

print(students)
# "Luke", "Leia", "Obi-Wan", "Han", "Chewie", "Lando"
				
			

Pop

The pop() function allows us to remove the value at the specified index. For example:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

# Remove Leia from the list:
students.pop(1)

print(students)
# "Luke", "Han", "Chewie", "Lando"
				
			

Note that you can also call the pop function without passing in an index, and it will default to -1, or the last value in the list. Try calling students.pop() with no parameter to see this.

Remove

The only difference between the pop() and remove() function is that rather than passing in an index, we pass in the actual value we want to remove. For example:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

# Remove Leia from the list:
students.remove("Leia")

print(students)
# "Luke", "Han", "Chewie", "Lando"
				
			

Note that if there are multiple elements with the same value, it will only remove the first instance of it in the list.

Reverse

The reverse() function simply reverses the order of the values in a list. For example:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]
students.reverse()

print(students)
# "Lando", "Chewie", "Han", "Leia", "Luke"
				
			

Sort

The sort() function will sort the values in a list according to some criteria. By default, the function will sort the values in alphabetical order (for strings), or least to greatest (for numbers), but you can also pass in the parameter Reverse=True to sort in Z-A or descending order. For example:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

# Sort alphabetically (A-Z) by default:
students.sort()

print(students)
# "Chewie", "Han", "Lando", "Leia", "Luke"

testScores = [92, 83, 88, 71, 79, 100, 95, 67, 70, 91]

# sort from highest to lowest score:
testScores.sort(reverse=True)

print(testScores)
# 100, 95, 92, 91, 88, 83, 79, 71, 70, 67
				
			

More List Functions

There are several other list functions that you can explore here.

Replit Practice

Loading...