|
1 | 1 | # list_operations_demo.py |
2 | | -# This script demonstrates basic list operations in Python such as append, insert, remove, reverse, extend, sort, and pop. |
| 2 | +# A demonstration of Python list methods including append, insert, remove, slicing, extend, sort, pop, membership check, and clear. |
3 | 3 |
|
4 | | -# Initial list |
| 4 | +# Create an initial list |
5 | 5 | List = [10, 20, 30, 40, 50] |
6 | | -print(List) # Output the original list |
| 6 | +print(List) # Output: [10, 20, 30, 40, 50] |
7 | 7 |
|
8 | | -# Append 60 to the end of the list |
| 8 | +# Append 60 to the list |
9 | 9 | List.append(60) |
10 | | -print(List) # List becomes: [10, 20, 30, 40, 50, 60] |
| 10 | +print(List) # Output: [10, 20, 30, 40, 50, 60] |
11 | 11 |
|
12 | 12 | # Print the length of the list |
13 | 13 | print(len(List)) # Output: 6 |
14 | 14 |
|
15 | 15 | # Insert 15 at index 2 |
16 | 16 | List.insert(2, 15) |
17 | | -print(List) # List becomes: [10, 20, 15, 30, 40, 50, 60] |
| 17 | +print(List) # Output: [10, 20, 15, 30, 40, 50, 60] |
18 | 18 |
|
19 | | -# Remove the first occurrence of 15 |
| 19 | +# Remove the value 15 |
20 | 20 | List.remove(15) |
21 | | -print(List) # List becomes: [10, 20, 30, 40, 50, 60] |
| 21 | +print(List) # Output: [10, 20, 30, 40, 50, 60] |
22 | 22 |
|
23 | | -# Create a reversed copy of the list using slicing |
| 23 | +# Create a reversed version of the list |
24 | 24 | list_reverse = List[::-1] |
25 | 25 | print(list_reverse) # Output: [60, 50, 40, 30, 20, 10] |
26 | 26 |
|
27 | | -# Find the index of the first occurrence of 40 |
| 27 | +# Find the index of value 40 |
28 | 28 | print(List.index(40)) # Output: 3 |
29 | 29 |
|
30 | | -# Create a new list and extend the original list with it |
| 30 | +# Extend the list with another list |
31 | 31 | new_List = [20, 30, 70, 60] |
32 | 32 | List.extend(new_List) |
33 | | -print(sorted(List)) # Print a sorted version of the list (does not modify original) |
| 33 | +print(sorted(List)) # Output: [10, 20, 20, 30, 30, 40, 50, 60, 60, 70] |
34 | 34 |
|
35 | 35 | # Remove the first occurrence of 20 |
36 | 36 | List.remove(20) |
37 | | -print(List) # 20 is removed from the first match only |
| 37 | +print(List) # Output: [10, 30, 40, 50, 60, 20, 30, 70, 60] |
38 | 38 |
|
39 | | -# Remove the last element from the list using pop |
| 39 | +# Remove the last item using pop() |
40 | 40 | List.pop() |
41 | | -print(List) # Last element (60) is removed |
| 41 | +print(List) # Output: [10, 30, 40, 50, 60, 20, 30, 70] |
| 42 | + |
| 43 | +# Check if 20 is still in the list |
| 44 | +if 20 in List: |
| 45 | + print("Yes") # Output: Yes |
| 46 | + |
| 47 | +# Clear all elements from the list |
| 48 | +List.clear() |
| 49 | +print(List) # Output: [] |
0 commit comments