summaryrefslogtreecommitdiffstats
path: root/generators.py
diff options
context:
space:
mode:
authorKyle K <kylek389@gmail.com>2017-04-01 03:34:41 -0500
committerKyle K <kylek389@gmail.com>2017-04-01 03:34:41 -0500
commita3d3368d9f024052632dc87b5d52e26a223c7869 (patch)
tree14f542224ba986030ea2a9424480a3975e4e72bb /generators.py
parent007a3ca9ea7c23f14341da104de47ecc919dfa77 (diff)
downloadPythonPractice-a3d3368d9f024052632dc87b5d52e26a223c7869.tar.gz
PythonPractice-a3d3368d9f024052632dc87b5d52e26a223c7869.tar.bz2
PythonPractice-a3d3368d9f024052632dc87b5d52e26a223c7869.zip
interator / generators exmaples
Diffstat (limited to 'generators.py')
-rw-r--r--generators.py34
1 files changed, 34 insertions, 0 deletions
diff --git a/generators.py b/generators.py
new file mode 100644
index 0000000..cdc0597
--- /dev/null
+++ b/generators.py
@@ -0,0 +1,34 @@
+
+# here is a simple generator
+# a 'yield' returns an expression which then gets invoked in for loop, a num by itself is an expression
+def gen1():
+ yield 1
+ yield 2
+ yield 3 # at this point python's list implemention will raise StopIteration since were at last yield
+
+a = [i for i in gen1()]
+print(a)
+
+
+# following example depicts how Comprehensions are syntactically almost the same except the use of () instead of []
+
+gen2 = ("{0} is even".format(i) for i in range(0, 10) if i % 2 == 0)
+print(gen2.__next__()) # get a value
+print(list(gen2)) # loop till the end
+#print(gen2.__next__()) # this would error, generator can only be looped once
+
+# output
+#
+# 0 is even
+# ['2 is even', '4 is even', '6 is even', '8 is even']
+
+
+
+# here is a Generator version of string reversal from interator.py
+
+def reverseString2(data):
+ for index in range(len(data) - 1, -1, -1):
+ yield data[index]
+
+for c in reverseString2('barfoo'):
+ print(c)