Skip to content

Commit 2fb7803

Browse files
committed
Add list.py to demonstrate list operations and manipulations in Python
1 parent 3c9fbd2 commit 2fb7803

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

List/list.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
tea_varities = ["black tea", "Green tea", "Oolong", "white"]
2+
print(tea_varities)
3+
4+
print(tea_varities[0]) # First item
5+
print(tea_varities[1:3]) # Slice: index 1 and 2
6+
7+
# Replace index 1 (Green tea) with each character of "Lemon" (bad idea)
8+
tea_varities[1:2] = "Lemon"
9+
print("Replacing with string splits each char:", tea_varities)
10+
11+
# Reset list
12+
tea_varities = ["black tea", "Green tea", "Oolong", "white"]
13+
# Replace slice with a list — correct way
14+
tea_varities[1:2] = ["lemon"]
15+
print("Proper replacement:", tea_varities)
16+
17+
# Replace two items with one
18+
tea_varities[1:3] = ["lemon"]
19+
print("Two replaced with one:", tea_varities)
20+
21+
# Insert at index 1 without removing anything
22+
tea_varities[1:1] = ["test", "test"]
23+
print("After inserting:", tea_varities)
24+
25+
# Remove a slice
26+
tea_varities[1:3] = []
27+
print("After deletion:", tea_varities)
28+
29+
# Looping through the list (line by line)
30+
for tea in tea_varities:
31+
print(tea)
32+
33+
# Looping with dash-separated print
34+
for tea in tea_varities:
35+
print(tea, end="-")
36+
print() # new line
37+
38+
# Membership check
39+
if "Oolong" in tea_varities:
40+
print("I have Oolong tea")
41+
42+
# Append "Oolang" (note the typo)
43+
tea_varities.append("Oolang")
44+
45+
# Membership check again (still "Oolong", not "Oolang")
46+
if "Oolong" in tea_varities:
47+
print("I have Oolong tea") # won't print
48+
49+
# Remove "green" (will cause error if not found)
50+
# tea_varities.remove("green") # ❌ Error: not in list
51+
52+
# So check before removing
53+
if "green" in tea_varities:
54+
tea_varities.remove("green")
55+
56+
# Insert "green" at index 1
57+
tea_varities.insert(1, "green")
58+
59+
# Copy list
60+
tea_varities_copy = tea_varities.copy()
61+
print("Copied list:", tea_varities_copy)
62+
63+
# Append original list to its copy (nested list)
64+
tea_varities_copy.append(tea_varities)
65+
print("Nested list:", tea_varities_copy)
66+
67+
# List comprehension
68+
squared_nums = [x**2 for x in range(10)]
69+
print("Squared numbers:", squared_nums)
70+
71+
# Just printing range object
72+
print("Range object:", range(10)) # shows: range(0, 10)
73+
print("Converted to list:", list(range(10))) # shows: actual list

0 commit comments

Comments
 (0)