Hello, Python developer! 😊
Hope you don't have any difficult on learning creaating, calling and modifying a List.
Today, we will learn the List functions. There are several useful functions for handling items in the List.
I showed list functions with usages.
List Functions
- Adding another list at the end of the List: List.extend(Another_List)
- Appending item in the List: list.append("Creed")
- Update item in the List: list.insert(update item index, update item)
- Remove item in the List: list.remove("item")
- Remove last item in the List: list.pop()
- Remove all items in the List: list.clear()
- Show the index number of item in the List: list.index("item"), if the item is not exist in the List, it shows error(ValueError: 'item' is not in list).
- Count the number of item in the List: list.count("item")
- Sort items in the List by increasing: list.sort()
- Reverse sort items in the List by decreasing: list.reverse()
- Copy list items from another list: list.copy(another list)
I showed all learning exercise codes and execution result as following screen shots.
lucky_numbers = [42, 18, 4, 8, 15, 16, 23]
friends = ["Kevin", "Karen", "Jim", "Jim", "JIM", "Oscar", "Toby"]
friends.extend(lucky_numbers)
friends.append("Creed")
friends.insert(1, "Kelly")
friends.remove("Toby")
lucky_numbers.sort()
print(friends)
friends.clear()
friends.extend(lucky_numbers)
print(friends)
friends = ["Kevin", "Karen", "Jim", "Jim", "JIM", "Oscar", "Toby"]
friends2 = friends.copy()
lucky_numbers.reverse()
friends2.extend(lucky_numbers)
print(friends2)
friends2.pop()
print(friends2)
print(friends2.index("Karen"))
friends2.pop()
print(friends2.count("Jim"))
friends2.clear()
Can you see the same result through Python codes? Congratulations, now you can manipulate items in the List as you want through list functions.
See you on next post, developer!
No comments:
Post a Comment