fork download
  1. # ================================
  2. # Chapter 7 – Lists & Tuples Demo
  3. # ================================
  4.  
  5. print("===== BASIC LIST CREATION =====")
  6. # List literals
  7. L1 = [1, 2, 3]
  8. L2 = ["a", "b", "c"]
  9. L3 = [1, "bill", 1.2345, True] # mixed types allowed
  10.  
  11. # Using the list() constructor from an iterable
  12. L_from_str = list("spam") # ['s','p','a','m']
  13. print("L1:", L1)
  14. print("L2:", L2)
  15. print("L3:", L3)
  16. print("L_from_str:", L_from_str)
  17. print()
  18.  
  19. print("===== LIST OPERATIONS (+, *, in, comparison) =====")
  20. L4 = [1, 2, 3] + [4]
  21. L5 = [1, 2, 3] * 2
  22. print("[1,2,3] + [4] ->", L4)
  23. print("[1,2,3] * 2 ->", L5)
  24. print("1 in [1,2,3] ->", 1 in [1, 2, 3])
  25. print("[1,2,3] < [1,2,4] ->", [1, 2, 3] < [1, 2, 4]) # lexicographic comparison
  26. print()
  27.  
  28. print("===== INDEXING & LIST OF LISTS =====")
  29. L_nested = ['a', [1, 2, 3], 'z']
  30. print("L_nested:", L_nested)
  31. print("L_nested[0] ->", L_nested[0])
  32. print("L_nested[1] ->", L_nested[1]) # inner list
  33. print("L_nested[1][0] ->", L_nested[1][0]) # nested index
  34. print()
  35.  
  36. print("===== BUILT-IN FUNCTIONS: len, min, max, sum =====")
  37. L_nums = [4, 7, 1, 2]
  38. print("L_nums:", L_nums)
  39. print("len(L_nums) ->", len(L_nums))
  40. print("min(L_nums) ->", min(L_nums))
  41. print("max(L_nums) ->", max(L_nums))
  42. print("sum(L_nums) ->", sum(L_nums))
  43. print()
  44.  
  45. print("===== ITERATION OVER LIST =====")
  46. for x in L_nums:
  47. print("Element:", x)
  48. print()
  49.  
  50. print("===== MUTABILITY: STR vs LIST =====")
  51. my_str = "abc"
  52. try:
  53. # This will raise an error (strings are immutable)
  54. # my_str[0] = 'z'
  55. print("Trying my_str[0] = 'z' would cause an error (immutable).")
  56. except TypeError as e:
  57. print("Error:", e)
  58.  
  59. my_list = [1, 2, 3]
  60. print("Original my_list:", my_list)
  61. my_list[0] = 127 # lists are mutable
  62. print("After my_list[0] = 127:", my_list)
  63. print()
  64.  
  65. print("===== COMMON LIST METHODS =====")
  66. my_list = ['a', 1, True]
  67. print("Start:", my_list)
  68.  
  69. # append
  70. my_list.append('z')
  71. print("After append('z'):", my_list)
  72.  
  73. # extend
  74. my_list.extend([10, 20])
  75. print("After extend([10,20]):", my_list)
  76.  
  77. # insert
  78. my_list.insert(1, "INSERTED")
  79. print("After insert(1,'INSERTED'):", my_list)
  80.  
  81. # remove
  82. my_list.remove('a')
  83. print("After remove('a'):", my_list)
  84.  
  85. # pop
  86. popped = my_list.pop() # pops last
  87. print("After pop() -> popped:", popped, ", list:", my_list)
  88.  
  89. # reverse
  90. my_list.reverse()
  91. print("After reverse():", my_list)
  92.  
  93. # sort (with numeric example)
  94. nums = [4, 7, 1, 2]
  95. print("\nnums before sort:", nums)
  96. ret = nums.sort() # in-place, returns None
  97. print("nums after sort():", nums)
  98. print("Return value of nums.sort() ->", ret)
  99. print()
  100.  
  101. print("===== RANGE AND LIST =====")
  102. # In Python 3, range is a range object, but list(range(...)) gives a list
  103. my_range_list = list(range(1, 5)) # [1,2,3,4]
  104. print("list(range(1,5)) ->", my_range_list)
  105. print()
  106.  
  107. print("===== STRING SPLIT RETURNS A LIST =====")
  108. s = "this is a test"
  109. split_list = s.split() # split on whitespace
  110. print("'this is a test'.split() ->", split_list)
  111. print()
  112.  
  113. print("===== SORTING: list.sort() vs sorted() =====")
  114. lst = list("xyzabc")
  115. print("lst original:", lst)
  116.  
  117. # in-place sort
  118. lst.sort()
  119. print("After lst.sort():", lst)
  120.  
  121. # sorted() returns new list
  122. s2 = "hi mom"
  123. sorted_chars = sorted(s2)
  124. print("sorted('hi mom') ->", sorted_chars)
  125. print()
  126.  
  127. print("===== REVERSE WORDS USING split + reverse + join =====")
  128. sentence = "hello world from python"
  129. words = sentence.split() # list of words
  130. words.reverse() # reverse list in-place
  131. rev_sentence = " ".join(words) # join with spaces
  132. print("Original sentence:", sentence)
  133. print("Reversed words:", rev_sentence)
  134. print()
  135.  
  136. print("===== MUTABILITY & SHARED REFERENCES =====")
  137. original = [1, 2, 3]
  138. alias = original # both name the same list
  139. alias[0] = 999
  140. print("original after alias[0]=999 ->", original)
  141.  
  142. print("\n===== SHALLOW COPY WITH [:] =====")
  143. L = [1, 2, [3, 4]]
  144. shallow = L[:] # top-level copy (shallow)
  145. shallow[0] = 100 # affects only shallow
  146. print("L:", L)
  147. print("shallow:", shallow)
  148.  
  149. # But inner list is shared:
  150. shallow[2][0] = 300
  151. print("\nAfter shallow[2][0] = 300")
  152. print("L:", L) # L also changed in nested list
  153. print("shallow:", shallow)
  154. print("Note: inner list is shared (shallow copy).")
  155. print()
  156.  
  157. print("===== TUPLES (IMMUTABLE LISTS) =====")
  158. T = (1, 2, 3)
  159. print("T:", T)
  160. print("T[0] ->", T[0])
  161.  
  162. # one-element tuple syntax
  163. t1 = (1,) # tuple
  164. t2 = (1) # just integer
  165. t3 = 1, # tuple
  166. print("t1 (1,) ->", t1, "type:", type(t1))
  167. print("t2 (1) ->", t2, "type:", type(t2))
  168. print("t3 1, ->", t3, "type:", type(t3))
  169.  
  170. print("\nTuple indexing, slicing, len work like lists:")
  171. print("T[1:] ->", T[1:])
  172. print("len(T) ->", len(T))
  173.  
  174. print("\nBut methods that modify lists are not allowed on tuples:")
  175. print("No T.append, T.extend, T.sort, etc. (would raise AttributeError).")
  176. print()
  177.  
  178. print("===== LIST COMPREHENSIONS – BASIC =====")
  179. # Basic: copy 1..4
  180. comp1 = [n for n in range(1, 5)]
  181. print("[n for n in range(1,5)] ->", comp1)
  182.  
  183. # Modify collected values: squares 1..5
  184. comp2 = [n**2 for n in range(1, 6)]
  185. print("[n**2 for n in range(1,6)] ->", comp2)
  186.  
  187. print("\n===== LIST COMPREHENSIONS – NESTED LOOPS =====")
  188. comp3 = [x + y for x in range(1, 4) for y in range(1, 4)]
  189. print("[x+y for x in range(1,4) for y in range(1,4)] ->", comp3)
  190.  
  191. print("\n===== LIST COMPREHENSIONS – WITH CONDITION =====")
  192. comp4 = [c for c in "Hi There Mom" if c.isupper()]
  193. print("[c for c in 'Hi There Mom' if c.isupper()] ->", comp4)
  194. print()
  195.  
  196. print("===== SIMPLE ANAGRAM CHECK USING SORTED LISTS =====")
  197. def are_anagrams(w1, w2):
  198. return sorted(w1) == sorted(w2)
  199.  
  200. print("are_anagrams('iceman', 'cinema') ->", are_anagrams("iceman", "cinema"))
  201. print("are_anagrams('hello', 'world') ->", are_anagrams("hello", "world"))
  202. print()
  203.  
  204. print("===== END OF CHAPTER 7 DEMO =====")
  205.  
Success #stdin #stdout 0.02s 7224KB
stdin
Standard input is empty
stdout
===== BASIC LIST CREATION =====
('L1:', [1, 2, 3])
('L2:', ['a', 'b', 'c'])
('L3:', [1, 'bill', 1.2345, True])
('L_from_str:', ['s', 'p', 'a', 'm'])
()
===== LIST OPERATIONS (+, *, in, comparison) =====
('[1,2,3] + [4] ->', [1, 2, 3, 4])
('[1,2,3] * 2  ->', [1, 2, 3, 1, 2, 3])
('1 in [1,2,3] ->', True)
('[1,2,3] < [1,2,4] ->', True)
()
===== INDEXING & LIST OF LISTS =====
('L_nested:', ['a', [1, 2, 3], 'z'])
('L_nested[0] ->', 'a')
('L_nested[1] ->', [1, 2, 3])
('L_nested[1][0] ->', 1)
()
===== BUILT-IN FUNCTIONS: len, min, max, sum =====
('L_nums:', [4, 7, 1, 2])
('len(L_nums) ->', 4)
('min(L_nums) ->', 1)
('max(L_nums) ->', 7)
('sum(L_nums) ->', 14)
()
===== ITERATION OVER LIST =====
('Element:', 4)
('Element:', 7)
('Element:', 1)
('Element:', 2)
()
===== MUTABILITY: STR vs LIST =====
Trying my_str[0] = 'z' would cause an error (immutable).
('Original my_list:', [1, 2, 3])
('After my_list[0] = 127:', [127, 2, 3])
()
===== COMMON LIST METHODS =====
('Start:', ['a', 1, True])
("After append('z'):", ['a', 1, True, 'z'])
('After extend([10,20]):', ['a', 1, True, 'z', 10, 20])
("After insert(1,'INSERTED'):", ['a', 'INSERTED', 1, True, 'z', 10, 20])
("After remove('a'):", ['INSERTED', 1, True, 'z', 10, 20])
('After pop() -> popped:', 20, ', list:', ['INSERTED', 1, True, 'z', 10])
('After reverse():', [10, 'z', True, 1, 'INSERTED'])
('\nnums before sort:', [4, 7, 1, 2])
('nums after sort():', [1, 2, 4, 7])
('Return value of nums.sort() ->', None)
()
===== RANGE AND LIST =====
('list(range(1,5)) ->', [1, 2, 3, 4])
()
===== STRING SPLIT RETURNS A LIST =====
("'this is a test'.split() ->", ['this', 'is', 'a', 'test'])
()
===== SORTING: list.sort() vs sorted() =====
('lst original:', ['x', 'y', 'z', 'a', 'b', 'c'])
('After lst.sort():', ['a', 'b', 'c', 'x', 'y', 'z'])
("sorted('hi mom') ->", [' ', 'h', 'i', 'm', 'm', 'o'])
()
===== REVERSE WORDS USING split + reverse + join =====
('Original sentence:', 'hello world from python')
('Reversed words:', 'python from world hello')
()
===== MUTABILITY & SHARED REFERENCES =====
('original after alias[0]=999 ->', [999, 2, 3])

===== SHALLOW COPY WITH [:] =====
('L:', [1, 2, [3, 4]])
('shallow:', [100, 2, [3, 4]])

After shallow[2][0] = 300
('L:', [1, 2, [300, 4]])
('shallow:', [100, 2, [300, 4]])
Note: inner list is shared (shallow copy).
()
===== TUPLES (IMMUTABLE LISTS) =====
('T:', (1, 2, 3))
('T[0] ->', 1)
('t1 (1,) ->', (1,), 'type:', <type 'tuple'>)
('t2 (1)  ->', 1, 'type:', <type 'int'>)
('t3 1,   ->', (1,), 'type:', <type 'tuple'>)

Tuple indexing, slicing, len work like lists:
('T[1:] ->', (2, 3))
('len(T) ->', 3)

But methods that modify lists are not allowed on tuples:
No T.append, T.extend, T.sort, etc. (would raise AttributeError).
()
===== LIST COMPREHENSIONS – BASIC =====
('[n for n in range(1,5)] ->', [1, 2, 3, 4])
('[n**2 for n in range(1,6)] ->', [1, 4, 9, 16, 25])

===== LIST COMPREHENSIONS – NESTED LOOPS =====
('[x+y for x in range(1,4) for y in range(1,4)] ->', [2, 3, 4, 3, 4, 5, 4, 5, 6])

===== LIST COMPREHENSIONS – WITH CONDITION =====
("[c for c in 'Hi There Mom' if c.isupper()] ->", ['H', 'T', 'M'])
()
===== SIMPLE ANAGRAM CHECK USING SORTED LISTS =====
("are_anagrams('iceman', 'cinema') ->", True)
("are_anagrams('hello', 'world')  ->", False)
()
===== END OF CHAPTER 7 DEMO =====