Lists & Loops

MPDA’22

October 28, 2021

Lists in python

In python, lists are defined using square brackets [].

x = [] # This is an empty list
y = [1,2,3,4] # This is a list of numbers

You can also access items on a list individually…

fruitList = ["organge","apple","strawberry"]
x = fruitList[0] # x = "orange
y = fruitList[2] # y = "strawberry"

…and in ranges of indexes separated by :

fruitList = ["apple", "banana", "cherry",
            "orange", "kiwi", "melon"]
x = fruitList[2:4]
# x = ["cherry", "orange", "kiwi"]

append() function

Adding objects to the end of a list

thisList = [] # An empty list
thisList.append("Something")
# now thisList = ["Something"]
thisList.append("Else")
# new thisList =["Something", "Else"]

insert() function

Adding an item at a specified index

thisList = ["dog","cow","cat"]
thisList.insert(1,"bird")
# thisList = ["dog", "bird", "cow","cat"]

remove() function

Removing an item from a list

thisList = ["dog","cow","cat"]
thisList.remove("cow")
# thisList = ["dog","cat"]

pop() function

Removing an item from a specified index

or the last index if no index is provided.

thisList = ["dog","cow","cat"]
thisList.pop()
# thisList = ["dog", "cow"]

thisList = ["dog","cow","cat"]
thisList.pop(0)
# thisList = ["cow", "cat"]

Built-in functions

range() function

The range() function returns a sequence of numbers…

  1. starting from 0 by default,
  2. and increments by 1 (by default),
  3. and ends at a specified number.
range(5) # Returns [0,1,2,3,4]

range(2,5) # Returns [2,3,4]

range(0,10,2) # Returns [0,2,4,6,8]

len() function

The len() function returns the current length of a list:

thisList = ["dog","cow","cat","bird"]
x = len(thisList)
# x = 4
thisList.append("bee")
x = len(thisList)
# x = 5

What are loops?

In computer science, a loop is a programming structure that repeats a sequence of instructions until a specific condition is met.

for VARIABLE_NAME in LIST_TO_ITERATE:
    # Code to be looped goes here!!
    # Everything inside the loop
    # should be INDENTED

Examples

Print each fruit in a fruit list

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

You can also loop through the letters of a word

for x in "banana":
    print(x)

loops can be nested

letters = ["A","B","C"]
numbers = ["1","2"]
result = []
for i in letters:
    # Iterate through all letters
    for j in numbers:
        # Iterate throught all numbers
        result.append(i+j)
# Once the loop finishes
# result = ["A1","A2","B1","B2","C1","C2"]

and combined with conditionals

numbers = [1,2,3,4,5,6]
even = []
odd = []
for num in numbers:
    if(num % 2 == 0):
        even.append(num)
    else:
        odd.append(num)

References

Generic resources

  1. Generic python
  2. Codility Code Challenges
  3. Rhino Developer Docs
  4. RhinoCommon API
  5. Python for Non-Programmers

Rhino/GH resources