-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13_list_method.py
More file actions
46 lines (35 loc) · 1.21 KB
/
13_list_method.py
File metadata and controls
46 lines (35 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Creating a list
my_list = [1, 2, 3]
# 1. append() - Add an item at the end
my_list.append(4)
print("append:", my_list) # [1, 2, 3, 4]
# 2. extend() - Add multiple elements
my_list.extend([5, 6])
print("extend:", my_list) # [1, 2, 3, 4, 5, 6]
# 3. insert() - Insert at a specific position
my_list.insert(2, 99)
print("insert:", my_list) # [1, 2, 99, 3, 4, 5, 6]
# 4. remove() - Remove first occurrence of an element
my_list.remove(99)
print("remove:", my_list) # [1, 2, 3, 4, 5, 6]
# 5. pop() - Remove and return last item (or by index)
popped_item = my_list.pop()
print("pop:", my_list, "popped:", popped_item) # [1, 2, 3, 4, 5], popped: 6
# 6. index() - Get the index of an element
index_of_3 = my_list.index(3)
print("index of 3:", index_of_3) # 2
# 7. count() - Count occurrences of an element
count_2 = my_list.count(2)
print("count of 2:", count_2) # 1
# 8. sort() - Sort the list
my_list.sort()
print("sort:", my_list) # [1, 2, 3, 4, 5]
# 9. reverse() - Reverse the list
my_list.reverse()
print("reverse:", my_list) # [5, 4, 3, 2, 1]
# 10. copy() - Copy the list
new_list = my_list.copy()
print("copy:", new_list) # [5, 4, 3, 2, 1]
# 11. clear() - Remove all elements
my_list.clear()
print("clear:", my_list) # []