4️⃣

6.4 Manipulating Lists

Manipulating Lists

Python provides many methods to manipulate lists.
You can view a complete list of them here
Below is an example of some of those methods in action:
# manipulating lists my_list = [] # empty list # append() adds elements to the end of the list my_list.append("live") my_list.append("long") my_list.append("and") my_list.append("prosper") print(my_list) # copy() returns a copy of the list copy_of_my_list = my_list.copy() print(copy_of_my_list) # pop() removes the element at the specified index my_list.pop(2) print(my_list) # remove() removes the first item with the specified value my_list.remove("live") print(my_list) # index() returns the index of the first element # with the specified value print(my_list.index("prosper")) # insert() adds an element at the specified position my_list.insert(0, "live") print(my_list) # reverse() reverses the order of the list my_list.reverse() print(my_list) # sort() sorts the list my_list.sort() print(my_list) # clear() removes all elements from the list my_list.clear() print(my_list)
Output of the following code:
2 4 [2, "oh no"] ["live", "long", "and", "prosper"] ["live", "long", "prosper"] ["long", "prosper"] 1 ["live", "long", "prosper"] ["prosper", "long", "live"] ["live", "long", "prosper"] []
View code on GitHub.
🚨
Remember: since these are methods, you have to do variable_name.method() in order to call them. Just doing method() will either not work as intended or error.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.