Skip to content

Commit 4f3e3a8

Browse files
authored
Add files via upload
1 parent 57dd405 commit 4f3e3a8

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

remove_from_list.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Python: del vs pop vs remove from a list
2+
# (c) Joe James 2023
3+
4+
def get_dogs():
5+
return ['Fido', 'Rover', 'Spot', 'Duke', 'Chip', 'Spot']
6+
7+
dogs = get_dogs()
8+
print(dogs)
9+
10+
# Use pop() to remove last item or an item by index and get the returned value.
11+
print('1. pop last item from list:')
12+
myDog = dogs.pop()
13+
print(myDog, dogs)
14+
15+
dogs = get_dogs()
16+
print('2. pop item with index 1:')
17+
myDog = dogs.pop(1)
18+
print(myDog, dogs)
19+
20+
# Use remove() to delete an item by value. (raises ValueError if value not found)
21+
dogs = get_dogs()
22+
print('3. remove first Spot from list:')
23+
dogs.remove('Spot')
24+
print(dogs)
25+
26+
# Use del to remove an item or range of items by index. Or delete entire list.
27+
dogs = get_dogs()
28+
print('4. del item with index 3:')
29+
del(dogs[3])
30+
print(dogs)
31+
32+
dogs = get_dogs()
33+
print('5. del items [1:3] from list:')
34+
del(dogs[1:3])
35+
print(dogs)
36+
37+
dogs = get_dogs()
38+
print('6. del entire list:')
39+
del(dogs)
40+
print(dogs)
41+
42+
43+
44+
45+
46+
47+
48+

0 commit comments

Comments
 (0)