2026-03-16_this-is-python.html


001| #:name::This is Python! (part 9)
002| #:link::https://thehardcorecoder.com/2026/03/16/this-is-python-part-9/
003| #:date::2026-03-16
004| #:code::
005| from examples import Point
006| 
007| pt = Point(3, 1, 4)
008| 
009| print(f'Point: {pt}')
010| print()
011| 
012| print('for-loop:')
013| for ix,elem in enumerate(pt):
014|     print(f'point[{ix}] = {elem}')
015| print()
016| 
017| print(f'list: {list(pt)}')
018| print(f'tuple: {tuple(pt)}')
019| print()
020| 
021| print(f'iter: {list(iter(pt))}')
022| print(f'enumerate: {list(enumerate(pt))}')
023| print(f'sorted: {list(sorted(pt))}')
024| print()
025| 
026| print(f'any: {any(pt)}')
027| print(f'all: {all(pt)}')
028| print(f'min: {min(pt)}')
029| print(f'max: {max(pt)}')
030| print(f'sum: {sum(pt)}')
031| print()
032| 
033| #:code::
034| from examples import Point
035| 
036| pt = Point(3, 1, 4)
037| 
038| print(f'Point: {pt}')
039| print()
040| 
041| print('Try indexing:')
042| try:
043|     print(f'[0] {pt[0]}')
044|     print(f'[1] {pt[1]}')
045|     print(f'[2] {pt[2]}')
046| 
047| except Exception as e:
048|     print(f'OOPS: {type(e).__name__}')
049|     print(e)
050| print()
051| 
052| print('Try getting the length:')
053| try:
054|     print(f'length: {len(pt)}')
055| 
056| except Exception as e:
057|     print(f'OOPS: {type(e).__name__}')
058|     print(e)
059| print()
060| 
061| print('Try reversing:')
062| try:
063|     print(f'reversed: {list(reversed(pt))}')
064| 
065| except Exception as e:
066|     print(f'OOPS: {type(e).__name__}')
067|     print(e)
068| print()
069| 
070| #:code::
071| """part of examples.py"""
072| 
073| class Point:
074|     '''A 3D XYZ Point class.'''
075| 
076|     ...
077| 
078|     def __iter__ (self):
079|         '''Return an iterator over the elements.'''
080|         return iter([self.x, self.y, self.z])
081| 
082|     def __len__ (self):
083|         '''Return length (always 3).'''
084|         return 3
085| 
086|     def __getitem__ (self, element_index):
087|         '''Return an element by index (x=0, y=1, z=2).'''
088|         if element_index == 0: return self.x
089|         if element_index == 1: return self.y
090|         if element_index == 2: return self.z
091| 
092|         # Invalid type...
093|         raise IndexError(f"Invalid index: {element_index}")
094| 
095|     def __setitem__ (self, element_index, new_value):
096|         '''Set an element by index (x=0, y=1, z=2).'''
097|         if element_index == 0: self.x = float(new_value); return
098|         if element_index == 1: self.y = float(new_value); return
099|         if element_index == 2: self.z = float(new_value); return
100| 
101|         # Invalid type...
102|         raise IndexError(f"Invalid index: {element_index}")
103| 
104|     def __delitem__ (self, element_index):
105|         '''Delete an element by index (not allowed).'''
106|         raise NotImplementedError(f"Point elements may not be deleted!")
107| 
108|     ...
109| 
110| #:code::
111| from examples import Point
112| 
113| pt = Point(3, 1, 4)
114| 
115| print(f'Point: {pt}')
116| print()
117| 
118| print(f'length: {len(pt)}')
119| print()
120| 
121| print('Getting values by index:')
122| try:
123|     print(f'[0] {pt[0]}')
124|     print(f'[1] {pt[1]}')
125|     print(f'[2] {pt[2]}')
126|     print(f'[3] {pt[3]}')
127| 
128| except Exception as e:
129|     print(f'OOPS: {type(e).__name__}')
130|     print(e)
131| print()
132| 
133| print('Changing values by index:')
134| try:
135|     pt[0] = 2
136|     print(f'[0] {pt[0]}')
137|     pt[1] = 7
138|     print(f'[1] {pt[1]}')
139|     pt[2] = 1
140|     print(f'[2] {pt[2]}')
141|     pt[3] = 8
142|     print(f'[3] {pt[3]}')
143| 
144| except Exception as e:
145|     print(f'OOPS: {type(e).__name__}')
146|     print(e)
147| print()
148| 
149| print(f'reversed: {list(reversed(pt))}')
150| print()
151| 
152| print('Try deleting:')
153| try:
154|     # Try to make it a 2D point...
155|     del pt[2]
156| 
157| except Exception as e:
158|     print(f'OOPS: {type(e).__name__}')
159|     print(e)
160| print()
161| 
162| #:code::
163| from examples import Point
164| 
165| pt = Point(2.11, 4.22, 6.33)
166| 
167| print(f'Point: {pt}')
168| print()
169| 
170| rv = reversed(pt)
171| print(f'reversed(pt) returned a {type(rv)}')
172| print(rv)
173| print()
174| 
175| try:
176|     print(f'length: {len(rv)}')
177| 
178| except Exception as e:
179|     print(f'OOPS: {type(e).__name__}')
180|     print(e)
181| print()
182| 
183| try:
184|     print(f'index: {rv[1]}')
185| 
186| except Exception as e:
187|     print(f'OOPS: {type(e).__name__}')
188|     print(e)
189| print()
190| 
191| print(f'make it a list: {list(rv)=}')
192| print(f'try that again: {list(rv)=} ??')
193| print()
194| 
195| print('for-loop:')
196| for elem in reversed(pt):
197|     print(elem)
198| print()
199| 
200| #:code::
201| # Difference between a list and its iterator...
202| from sys import getsizeof
203| 
204| # Create a big list...
205| big_list = list(range(1_000_000))
206| 
207| print(f'list length: {len(big_list):,} items')
208| print(f'list size: {getsizeof(big_list):,} bytes')
209| print()
210| 
211| print(f'first 3 list items: {big_list[:3]}')
212| print(f'last 3 list items: {big_list[-3:]}')
213| print()
214| 
215| # Get a big list iterator...
216| list_iter = iter(big_list)
217| 
218| print(f'iterator size: {getsizeof(list_iter):,} bytes')
219| print()
220| 
221| print(f'iter item: {next(list_iter)}')
222| print(f'iter item: {next(list_iter)}')
223| print(f'iter item: {next(list_iter)}')
224| print('...')
225| print()
226| 
227| #:code::
228| # Alternate way to reverse a list...
229| 
230| # Strings are lists, so...
231| message = "Hello, World!"
232| 
233| print(f'forward: {message}')
234| print(f'reverse: {message[::-1]}')
235| print()
236| 
237| items = [1, 2, 3, 'a', 'b', 'c']
238| 
239| print(f'forward: {items}')
240| print(f'reverse: {items[::-1]}')
241| print()
242| 
243| #:code::
244| """part of examples.py"""
245| 
246| class Point:
247|     '''A 3D XYZ Point class.'''
248| 
249|     ...
250| 
251|     def __reversed__ (self):
252|         '''Return a reversed generator.'''
253|         def generator ():
254|             '''Generator function with reversed elements.'''
255|             yield self.z
256|             yield self.y
257|             yield self.x
258| 
259|         # Return a new generator...
260|         return generator()
261| 
262|     ...
263| 
264| #:code::
265| """(not a) part of examples.py"""
266| 
267| class Point:
268|     '''A 3D XYZ Point class.'''
269| 
270|     ...
271| 
272|     def __reversed__ (self):
273|         '''Return a reversed list.'''
274|         return [self.z, self.y, self.x]
275| 
276|     ...
277| 
278| #:code::
279| from examples import Point
280| 
281| pt = Point(2.11, 4.22, 6.33)
282| 
283| print(f'Point: {pt}')
284| print()
285| 
286| rv = reversed(pt)
287| print(f'reversed(pt) returned a {type(rv)}')
288| print(rv)
289| print()
290| 
291| print(f'length: {len(rv)=}')
292| print()
293| 
294| print(f'index: {rv[0]=}')
295| print(f'index: {rv[1]=}')
296| print(f'index: {rv[2]=}')
297| print()
298| 
299| print(f'make it a list: {list(rv)=}')
300| print(f'try that again: {list(rv)=} !!')
301| print()
302| 
303| print('for-loop:')
304| for elem in reversed(pt):
305|     print(elem)
306| print()
307| 
308| #:code::
309| """(not a) part of examples.py"""
310| 
311| class Point:
312|     '''A 3D XYZ Point class.'''
313| 
314|     ...
315| 
316|     def __reversed__ (self):
317|         '''Return a reversed list.'''
318|         return iter([self.z, self.y, self.x])
319| 
320|     ...
321| 
322| #:code::
323| def the_reversed_function (list_like_object):
324|     '''Simple example implementation of reversed.'''
325| 
326|     # Get number of items in list...
327|     index = list_like_object.__len__()
328| 
329|     # While items are in list...
330|     while 0 < index:
331| 
332|         # Decrement the index...
333|         index -= 1
334| 
335|         # Get the indexed item...
336|         item = list_like_object.__getitem__(index)
337| 
338|         # Yield the item
339|         yield item
340| 
341| 
342| items = list(range(12))
343| 
344| rv = the_reversed_function(items)
345| print(f'{rv}')
346| print(f'{type(rv)=}')
347| print(f'{list(rv)=}')
348| print(f'{list(rv)=}')
349| print()
350| 
351| #:note:: {P}_\text{add}=\left[\;({x}_{p_1}\!+\!{x}_{p_2})\,,\;\;({y}_{p_1}\!+\!{y}_{p_2})\,,\;\;({z}_{p_1}\!+\!{z}_{p_2})\;\right]
352| #:note:: {P}_\text{add}=\left[\;({x}_{p_1}\!+\!{N})\,,\;\;({y}_{p_1}\!+\!{N})\,,\;\;({z}_{p_1}\!+\!{N})\;\right]
353| #:note:: <p style="padding-left: 20px;">$latex {P}_\text{add}=\left[\;({x}_{p_1}\!+\!{x}_{p_2})\,,\;\;({y}_{p_1}\!+\!{y}_{p_2})\,,\;\;({z}_{p_1}\!+\!{z}_{p_2})\;\right] &amp;s=0&amp;fg=000080$</p>
354| #:note:: <p style="padding-left: 20px;">$latex {P}_\text{add}=\left[\;({x}_{p_1}\!+\!{N})\,,\;\;({y}_{p_1}\!+\!{N})\,,\;\;({z}_{p_1}\!+\!{N})\;\right] &amp;s=0&amp;fg=000080$</p>
355| #:code::
356| """part of examples.py"""
357| 
358| class Point:
359|     '''A 3D XYZ Point class.'''
360| 
361|     ...
362| 
363|     def __add__ (self, other):
364|         '''Add two points or scalar, return sum in new Point.'''
365| 
366|         # A scalar adds to each member...
367|         if isinstance(other,int) or isinstance(other,float):
368|             x = self.x + other
369|             y = self.y + other
370|             z = self.z + other
371|             return Point(x, y, z)
372| 
373|         # A vector adds memberwise...
374|         if isinstance(other, type(self)):
375|             x = self.x + other.x
376|             y = self.y + other.y
377|             z = self.z + other.z
378|             return Point(x, y, z)
379| 
380|         # Invalid type...
381|         raise ValueError(f"Can't add a {typename(other)}!")
382| 
383|     def __iadd__ (self, other):
384|         '''Add another point or scalar to self; return self.'''
385| 
386|         # A scalar adds to each member...
387|         if isinstance(other,int) or isinstance(other,float):
388|             self.x += other
389|             self.y += other
390|             self.z += other
391|             return self
392| 
393|         # A vector adds memberwise...
394|         if isinstance(other, type(self)):
395|             self.x += other.x
396|             self.y += other.y
397|             self.z += other.z
398|             return self
399| 
400|         # Invalid type...
401|         raise ValueError(f"Can't add a {typename(other)}!")
402| 
403|     def __radd__ (self, other):
404|         '''Add scalar number to self; return new Point.'''
405| 
406|         # Only called when X + Point, so X is never a Point...
407|         if isinstance(other,int) or isinstance(other,float):
408|             return self.__add__(other)
409| 
410|         # Invalid type...
411|         raise ValueError(f"Can't add a {typename(other)}!")
412| 
413|     ...
414| 
415| #:code::
416| """part of examples.py"""
417| 
418| class Point:
419|     '''A 3D XYZ Point class.'''
420| 
421|     ...
422| 
423|     def __radd__ (self, other):
424|         '''Add scalar number to self; return new Point.'''
425| 
426|         return self.__add__(other)
427| 
428|     ...
429| 
430| #:code::
431| """part of examples.py"""
432| 
433| class Point:
434|     '''A 3D XYZ Point class.'''
435| 
436|     ...
437| 
438|     def __add__ (self, other):
439|         ...
440| 
441|     __radd__ = __add__
442| 
443|     ...
444| 
445| #:end:code::
446|