This notebook covers lists and for-loops. These will prove to useful in future notebooks. Naturally this tutorial is broken up into lists, for-loops, and for-loops over lists.
Lists
A list comprises strings, numbers, and even abstract class instances. Items in a list are changeable in the sense that we can alter add, remove, or alter existing list entries. A list also permits duplicates, and thus, items in a list do not have to be unique. A given item in a list may also be another list.
Each item in a list can be referenced by its index, i.e., the order of its appearance in the list. Consider the following list
As noted above, python starts counting at 0. A list has a length, corresponding to the number of items it contains. Items in a list can be removed; items can also be appended to a list.
Code
todays_terms.remove("Bernoulli")print(todays_terms)todays_terms.append(0.001)print(todays_terms)todays_terms.insert(3, "adding") # "adding" inserted in position 3print(todays_terms)tomorrows_terms = todays_terms.copy()print(tomorrows_terms)tomorrows_terms.pop(5) # Removing the 5th entryprint(tomorrows_terms)
[<__main__.Cards object at 0x107b0ce50>, <__main__.Cards object at 0x107b0cf90>, <__main__.Cards object at 0x107b0d090>]
For loops
In python the for loop is used for iterating. However, unlike many other languages, it can iterate over a list, strings, or even other sequences (such as dictionaries and tuples). First, consider the standard use where we iterate across a range of integers.
Code
for i inrange(0, 10): # iterating between 0 and 9print(i)
0
1
2
3
4
5
6
7
8
9
Code
for i inrange(0, 10, 2): # iterating between 0 and 9, whilst skipping every 2nd entryprint(i)
0
2
4
6
8
Code
for card in my_list: # iterating our list of cardsprint(card.name)