-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathbrisk_python.Rmd
1464 lines (1077 loc) · 35.6 KB
/
brisk_python.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
jupyter:
jupytext:
notebook_metadata_filter: all,-language_info
split_at_heading: true
text_representation:
extension: .Rmd
format_name: rmarkdown
format_version: '1.2'
jupytext_version: 1.13.7
kernelspec:
display_name: Python 3
language: python
name: python3
---
# Brisk introduction to Python
This is an introduction designed for those of us who already know a [dynamic
programming
language](https://en.wikipedia.org/wiki/Dynamic_programming_language) fairly
well. MATLAB and the R language are [examples of dynamic programming
languages](https://en.wikipedia.org/wiki/Dynamic_programming_language#Examples_of_Dynamic_Programming_Languages).
For an alternative introduction at a slightly slower pace, see [Introducing
Python](./introducing_python.Rmd).
## Numbers
There are two types of numbers in Python: integer and floating point.
You may remember that an integer is a whole number - a number without anything
after the decimal point. The *counting numbers* are integers — e.g. 0, 1, 2,
3, .... But integers also include negative whole numbers — e.g. -1, -2, -3
...
In Python, an integer is an *object* of type `int`, and a float is an object
of type `float`.
```{python}
a = 99
type(a)
```
```{python}
b = 99.0
type(b)
```
You can create ints and floats by using `int` and `float` like this:
```{python}
float('1')
```
```{python}
float(1)
```
```{python}
int('1')
```
```{python}
int(1)
```
`+`, `-`, `\*` or `/` on a mix of floats and ints, give floats:
```{python}
a + b
a * b
```
Dividing an int by an int also gives a float:
```{python}
1 / 2
```
If you only want the integer part of the division, use `//`
```{python}
1 // 2
```
```{python}
1.0 // 2.0
```
Python has built-in function called `round`:
```{python}
round(5.0 / 2.0)
```
Built-in means it is always available in Python, without you having to load an optional module (library). You will see modules soon.
The `%` operator on numbers gives you the remainder of integer division
(also known as the modulus):
```{python}
5 % 2
```
```{python}
5.0 % 2.0
```
(true-and-false)=
## True and False
`True` and `False` are special objects in Python. They are of type `bool`
(for Boolean).
```{python}
type(True)
```
```{python}
type(False)
```
To show several results from one cell, we can use the `print` function, that
displays the value. As you will soon see, we use a function by giving its
name (here: `print`) followed by round brackets (parentheses) that contain the
thing or things we want the function to work on. For example, to display the
value `False` I can write:
```{python}
print(False)
```
This is similar to what I would get by just putting `False` on the last line of the cell, in the way we have been doing up to now, to show values. One advantage of `print` is that I can display multiple values from one cell:
```{python}
print(True == False)
print(True == True)
print(False == False)
```
## None
`None` is also a special object in Python. By convention, Python often uses
`None` to mean that no valid value resulted from an operation, or to signal
that we don’t have a value for a parameter.
```{python}
type(None)
```
Unlike most other values in Python, the default display output from None, is
nothing:
```{python}
None
```
## Equals
As for MATLAB and R, `=` is for assignment, `==` is for testing equality.
```{python}
# a gets the value 1. Notice the single =
a = 1
a
```
`==` is a test to ask if the left hand side value is equal to the right hand side value:
```{python}
a == 1
```
Notice that Python returns True in this case because `a` is equal to 1. On the other hand:
```{python}
a == 2
```
Like R, Python uses `!=` for testing that objects are *not* equal. This is
different from MATLAB, which uses `~=`:
```{python}
a != 1
```
(comparison-operators)=
## Comparison operators
You have just seen the `==` *operator* in action, as well as the `!=`
operator.
These are *operators* because they operate on values. Here they operate on the values to their left and right.
`+` and `-` and so on, are also operators. You can read this:
```{python}
3 + 4
```
as "Apply the addition operator to 3 and 4, returning the result (here, 7).
Similarly, you can read:
```{python}
a == 2
```
as "Apply the equality operator to the value in `a` and 2, returning the
result (here, `True`).
The equality operator `==` and the inequality operator `!=` are examples of
*comparison* operators. These are operators that apply a *comparison*
question to the values to their left and right. They always return True or False.
Here are Python's comparison operators:
| Operator | Name | Example | Result for example |
| --- | --- | --- | --- |
| `==` | equal to | `3 == 2` | `False` |
| `!=` | not equal to | `3 != 2` | `False` |
| `<` | less than | `2 < 3` | `True` |
| `>` | greater than | `2 > 3` | `False` |
| `<=` | less than or equal to | `2 <= 2` | `True` |
| `>=` | greater than or equal to | `2 >= 2` | `True` |
Here are the examples:
```{python}
print('3 == 2 gives', 3 == 2)
print('3 != 2 gives', 3 != 2)
print('2 < 3 gives', 2 < 3)
print('2 > 3 gives', 2 > 3)
print('2 <= 2 gives', 2 <= 2)
print('2 >= 2 gives', 2 >= 2)
```
## Logical operators
Logical operators are like comparison operators, but they ask *logical* questions.
For example, in logic, by definition, the *and* operator asks the question:
*Are both the left and right values True?* — like this:
```{python}
print('True and True:', True and True)
print('True and False:', True and False)
print('False and True:', False and True)
print('False and False:', False and False)
```
Similarly, the logical operator *or* asks the question: "Is either of the left or the right values True?". The answer is True to the question if either the left value is True, or the right, or both:
```{python}
print('True or True:', True or True)
print('True or False:', True or False)
print('False or True:', False or True)
print('False or False:', False or False)
```
The operator *not* only works on the value to its left, and it flips a True
value to False, or a False value to True.
```{python}
print('not True:', not True)
print('not False:', not False)
```
In fact, the logical operators will first force their arguments to be True or False before they give their answer. So, in the case of `and` or `or`, they force force their left and right arguments to be `bool` values, before they calculate the answer. So, in fact, you can use things other than exact True and False on either side of the `and` or `or`, as long as applying `bool(value)` to the thing to the left and right will produce a True or False value. See {doc}`truthiness` for more detail.
## “If” statements, blocks and indentation
A conditional statement in Python looks like this:
```{python}
my_var = 10
if my_var == 10:
print("The conditional is True!")
print("my_var does equal 10")
```
The first line of the conditional statement, that contains the conditional
test, ends in a colon. Call this the *if test*. There follow some lines
*indented* relative to the `if` test. Call these indented lines the *if
block*. Python executes the statements in the `if` block only when the
`if` test evaluates to True. For example, in this case, the `if` test
evaluates to False, and the block does not execute:
```{python}
my_var = 11
# This time the conditional evaluates to False
if my_var == 10: # the "if test"
# The indented lines are the "if block"
print("The conditional is True!")
print("my_var does equal 10")
```
The first line that returns to the same level of indentation as the `if`
test line, closes the `if` block.
Unless the `if` block has a further indented block (for example, another
`if` block), then all the lines in the block must have the same indentation.
See note for equivalent `if` statements in R
and MATLAB.
The `if` block may be followed by another block where the conditional is
`else:`. This block will only run if the initial conditional test evaluates
to False.
```{python}
my_var = 11
if my_var == 10:
print("The conditional is True!")
print("my_var does equal 10")
else:
print("The conditional is False!")
print("my_var does not equal 10")
```
There may be other conditional tests, with associated conditional blocks.
These tests use the contraction `elif conditional_test`, where `elif` is a
contraction for `else if`:
```{python}
my_var = 12
if my_var == 10:
print("The conditional is True!")
print("my_var does equal 10")
elif my_var == 11:
print("The second conditional is True!")
print("my_var does equal 11")
elif my_var == 12:
print("The third conditional is True!")
print("my_var does equal 12")
else:
print("All conditionals are False!")
print("my_var does not equal 10, 11 or 12")
```
## “While” statements
`while` statements are another example with an initial test followed by an
indented block. Here’s an example where we find the largest [Fibonacci
number](https://en.wikipedia.org/wiki/Fibonacci_number) less than 1000:
```{python}
last_but_1 = 0
fibonacci = 1
while fibonacci < 1000:
last_but_2 = last_but_1
last_but_1 = fibonacci
fibonacci = last_but_2 + last_but_1
print("Largest Fibonacci < 1000 is", last_but_1)
```
Notice the initial *while test*: `while fibonacci < 1000:`, followed by the
indented *while block*. Unlike the `if` statement, Python will continue to
run the statements in the `while` block until the conditional in the
`while` test evaluates to False.
## Lists
Make a list like this:
```{python}
my_list = [9, 4, 7, 0, 8]
my_list
```
```{python}
type(my_list)
```
A list element can be any type of object, including another list:
```{python}
mixed_list = [9, 3.0, True, my_list]
mixed_list
```
```{python}
type(mixed_list)
```
A Python list is like a cell array in MATLAB, or a `list` in R.
## “for” loops and iteration
We can *iterate* over a list. To iterate, means to fetch one element after
another from some container, such as a list. We can use a `for` loop to
iterate over a list:
```{python}
for e in my_list:
print(e)
```
The `for` loop has the same form as `if` statements and `while` loops,
with a first line ending in a colon, followed by an indented block.
The first line in the `for` loop is of form: `for loop_variable in
container:`. The *container* is the container from which we will fetch the
elements. At each iteration of the `for` loop, Python gets a new element
from the container to put into the *loop variable*. For each element in the
container, Python executes the *for block*.
Note shows equivalent `for` loops in Python, R and
MATLAB.
See
[`range`](https://docs.python.org/3/library/functions.html#func-range)
for a common way of writing a `for` loop that iterates over a sequence of
integers.
## Lists are sequences
A [sequence](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range)
is a category of Python objects that have a defined element order, have a
length, are iterable, can be indexed with integers, and *sliced* (see below).
If object `s` is a sequence, then:
* `s` has a length that can be found with `len(s)`;
* we can iterate over the elements in `s` with `for element in s: # do
something with element`;
* we can return the element at position `n` with `s[n]`;
* we can get another sequence by *slicing* `s`. For example, `s[0:n]`
will give a new sequence containing the first `n` elements of `s`.
```{python}
# Has a length
len(my_list)
```
```{python}
# Is iterable
for e in my_list:
print(e)
```
```{python}
# Can be indexed
my_list[1]
```
```{python}
# Can be sliced
my_list[0:2]
```
## Python indices are 0-based
Indices for Python sequences start at 0. For Python, the first element is at
index 0, the second element is at index 1, and so on:
```{python}
# the first element
my_list[0]
```
```{python}
# the second element
my_list[1]
```
## Negative indices
Negative numbers as indices count back from the end of the list. For
example, use index `-1` to return the last element in the list:
```{python}
print(my_list)
# the last element
my_list[-1]
```
This is the third from last element:
```{python}
my_list[-3]
```
## Lists are mutable
A list is a *mutable* object. Mutable means, that we can change the elements
in the list, without creating a new list.
```{python}
my_list[1] = 99
my_list
```
In Python, variable names point to an object.
When you do `another_variable = a_variable`, you are telling the name
`another_variable` to point to the same object as the name
`a_variable`. When objects are mutable, this can be confusing:
```{python}
another_list = my_list
another_list
```
`my_list` points to a list object in memory. When you do
`another_list = my_list`, it tells Python that `another_list` points
to *the same object*. So, if we modify the list, pointed to by
`my_list`, we also modify the value of `another_list`, because `my_list`
and `another_list` point at the same list.
```{python}
my_list[1] = 101
another_list
```
## Adding lists
Adding two lists with `+` returns a new list that is the concatenation of
the two lists:
```{python}
new_list = my_list + [False, 1, 2]
new_list
```
## Appending and removing elements
You can append elements with the `append` method.
A method is a function attached to the object. See Functions for more
on functions in Python.
We can see that `append` is a method by displaying the value of
`my_list.append`:
```{python}
my_list.append
```
To call the method, we add parentheses, surrounding any arguments we want to
pass into the method. In this case we want to pass in the element to append:
```{python}
my_list.append(20)
my_list
```
Note that the `append` method does *not* return the list, it just changes
the list in-place. Python returns `None` from the `append` method:
```{python}
result = my_list.append(42)
result == None
```
This is also true for some other methods that modify the list in-place, such
as the `sort` method:
```{python}
new_list = [10, 1, 3]
result = new_list.sort()
# Return value is None
result == None
# But the original list now in ascending order from sort
new_list
```
You can remove elements from the list with the `pop` method:
```{python}
# Remove and return the last element of the list
my_list.pop()
my_list
```
```{python}
# Remove and return the third element of the list
my_list.pop(2)
my_list
```
## Slicing
You can return slices from any sequence, including lists, by putting a slice
specifier in square brackets. For example, this returns the first 3 elements
of the list:
```{python}
my_list[0:3]
```
The first number after the square bracket and before the colon is the *start*
index. In this case we start at the first element (element at index 0). The
second number, after the colon, is the *stop* index. This is the end index
*plus one*. So we return elements at index 0, 1 and 2. That is, elements *up
to, but not including* 3.
If you omit the first number (the start index) Python assumes 0:
```{python}
my_list[:3]
```
If you omit the second number, Python assumes the length of the list as
the stop index.
```{python}
my_list[2:]
```
```{python}
my_list[2:len(my_list)]
```
You can omit both numbers, in which case you return all the elements of the
list. This can be useful if you want to make a new list that contains the same
elements as the first:
```{python}
another_list = my_list[:]
another_list
```
Because this is a new list object, you can change the original list without
changing the new list:
```{python}
my_list[1] = 999
another_list
```
You can also specify a second colon, and a third number. This third
number is the *step size*. For example, to get every second element of
the list:
```{python}
my_list[0:len(my_list):2]
```
```{python}
# Length of list assumed as stop index if omitted
my_list[0::2]
```
You can use negative numbers for the `start` and `stop` indices. As for
indexing, negative `start` and `stop` values count back from the end of
the list:
```{python}
print(my_list)
my_list[-4:-2]
```
Negative numbers for the `step` count backwards from the `start` to the
`stop` index:
```{python}
my_list[4:1:-1]
```
If you have a negative step size, and you don’t specify the start index, then
the start index defaults to the last element in the list. If you don’t specify
the stop index, it defaults to one prior to index 0:
```{python}
print(my_list)
my_list[-1:1:-1]
```
```{python}
my_list[:1:-1]
```
```{python}
my_list[-2::-1]
```
One consequence that is worth remembering is that the following idiom gives
you a reversed copy of the list:
```{python}
my_list[::-1]
```
(tuples)=
## Tuples
Tuples are almost the same as lists, except they are not mutable. That
is, you cannot change the elements of a tuple, or change the number of
elements.
```{python}
my_tuple = (9, 4, 7, 0, 8)
my_tuple
```
```{python tags=c("raises-exception")}
# This raises a TypeError
my_tuple[1] = 99
```
```{python tags=c("raises-exception")}
# This raises an AttributeError, because tuples have no append method
my_tuple.append(20)
```
Here’s an empty tuple:
```{python}
empty_tuple = ()
empty_tuple
```
A tuple with two elements:
```{python}
two_tuple = (1, 5)
two_tuple
```
As with lists, you can add tuples, forming the concatenation of the tuples:
```{python}
(1, 2) + (5, 6)
```
There is a little complication when making a tuple with one element:
```{python}
not_a_tuple = (1)
not_a_tuple
```
This is because Python can’t tell that you meant this to be a tuple, rather
than an expression with parentheses round it. See {doc}`length_one_tuples` for
an explanation.
To tell Python that you mean this to be a length-one tuple, add a comma after
the element, and before the closing parenthesis:
```{python}
length_one_tuple = (1,)
length_one_tuple
```
## Strings
Make a string like this:
```{python}
my_string = 'interesting text'
my_string
```
You can use single quotes or double quotes for your string, the two strings
are the same:
```{python}
another_string = "interesting text"
another_string
my_string == another_string
```
Convert other objects to strings using `str`:
```{python}
# Convert integer to string
str(9)
```
```{python}
# Convert floating point value to string
str(1.2)
```
## Strings are sequences
Like lists, strings are sequences (have length, can be iterated, can index,
can slice).
```{python}
# Length
len(my_string)
```
```{python}
# Iterable
for c in my_string:
print(c)
```
```{python}
# Can index
my_string[1]
```
```{python}
# Can slice
my_string[1:5]
```
```{python}
# Can slice
my_string[::-1]
```
## Strings are immutable
Unlike lists, strings are immutable. You cannot change the characters within a
string:
```{python tags=c("raises-exception")}
# Raises a TypeError
my_string[1] = 'N'
```
## Adding strings
```{python}
my_string + ' with added insight'
```
## String methods
Strings have lots of interesting methods. In IPython, try tab-complete on a
string variable name, followed by a period – e.g. type `my_string.`,
followed by the tab key. See also the [list of string methods in the Python
docs](http://docs.python.org/library/stdtypes.html#string-methods).
One interesting method is `replace`. It returns a new string that is a copy
of the input, but replacing instances of one string with another:
```{python}
another_string = my_string.replace('interesting', 'extraordinary')
another_string
```
Notice that the original string has not changed (it’s immutable):
```{python}
my_string
```
Use the `split` method to break a string into a list of strings. By
default, `split` will split the string at any white space (spaces, tab
characters or line breaks):
```{python}
my_string.split()
```
Pass a character to `split` to split the string at that character:
```{python}
another_example = 'one:two:three'
another_example.split(":")
```
The `strip` method returns a new string with spaces, tabs and end of line
characters removed from the beginning and end of the string:
```{python}
# A string with a newline character at the end
my_string = ' a string\n'
my_string
my_string.strip()
```
## Inserting values into strings
We often want to insert values into strings. This is called *string interpolation*.
For example, let us say we are running a shepherding business. The shepherds rotate, some days Mary is on, sometimes Joseph, sometimes their son James.
Today, Mary is on.
```{python}
shepherd_name = "Mary"
```
She is herding 92 sheep.
```{python}
flock_size = 92
```
We may want to send out an announcement, say to the LED message board in front
of our shepherding business, that tells people which shepherd is on duty, and how many sheep they have.
So, if the number of sheep is 92, the message could be any of these three:
* "Shepherd Mary is on duty with 92 sheep." or
* "Shepherd Joseph is on duty with 92 sheep." or
* "Shepherd James is on duty with 92 sheep."
depending on the value in the `shepherd_name` variable. And, of course, the `flock_size` could be almost any number. So there are a huge number of potential sentences, that depend on the `shepherd_name` variable, and the `flock_size` variable.
Usually the best way to do this is using something called
[f-strings](https://datagy.io/python-f-strings). These are strings with an `f` before the opening quote. The `f` tells Python you may want to insert a variable into the string. You specify variables to insert by putting them inside curly braces (`{}`) in the string, like this:
```{python}
# Notice the f before the first quote to tell Python there may
# be variables inside this string.
f"Shepherd {shepherd_name} is on duty with {flock_size} sheep."
```
There are many ways you can tell Python how to format the values you insert, and there are other, less common and useful ways to do this string interpolation.
For more details and more options, see: [Inserting values into strings](./string_formatting.Rmd).
## Range
`range` returns a *range object*. It is a sequence, and so it is rather like
a list . When you use `range` with one argument, the argument value is the
`stop` index. For example, to make a `range` object generating the numbers
from 0 up to *but not including* 5:
```{python}
my_range = range(5)
my_range
```
You can make a range object into a list by using `list`:
```{python}
list(range(5))
```
A `range` object is a sequence:
```{python}
# Has a length
print('Length', len(my_range))
# Is iterable
for e in my_range:
print('Value', e)
# Can be indexed
print('Value at position 1', my_range[1])
# Can be sliced
print('Slice 0:2', my_range[0:2])
```
Set the start element for `range` by passing two arguments:
```{python}
my_range = range(1, 7)
print(my_range)
print(list(my_range))
```
Set the step size with a third argument:
```{python}
my_range = range(1, 7, 2)
list(my_range)
```
One common use of `range` is to iterate over a sequence of numbers in a `for`
loop:
```{python}
for i in range(5):
print(i)
```
## Sets
Sets are collections of unique elements, with no defined order. Python
reserves the right to order set elements in any way it chooses:
```{python}
# Only unique elements collected in the set
my_set = set((5, 3, 1, 3))
my_set
```
Because there is no defined order, you cannot index into a set:
```{python tags=c("raises-exception")}
my_set[1]
```
You can add elements to a set with the `add` method:
```{python}
my_set.add(10)
my_set
```
Because set elements must be unique, if you add an element already in the set,
this does not change the set: