Storing and Modifying Different Kinds of Data

Author
Dr. Ole Bialas

Writing experimental applications requires representing different kinds of data: text prompts that are presented to the participant, lists that store trial sequences or responses and experimental parameters like stimulus intensity or trial duration. This session intoduces some of the most important data types that are available in Python and explores the operations that can be performed on them.

Section 1: Data Types and Variables

Programs receive, create and operate on data. There are many different types but a few essential ones can be found in most programming languages. In Python, they are called:

  • int: integers or non-decimal numbers, example -7, 0, 101
  • float: floating-point numbers with a limited number of decimal places, for example: 0.1, pi, 1/3
  • str: a string of characters, marked by quotations, for example “a”, “13”, “hello”
  • bool: boolean logical values, can be either True or False

The type determines the range of values the data can take on as well as the set of operations that can be performed on them (more on this in the next section). In this section, you’ll learn how assign data to variables, get their data type and convert them from one data typpe to another.

Code Description
x = 3 Assign the integer number 3 to the variable x
x = 3.14 Assign the floating number 3.14 to the variable x
x = "hi" Assign the string "hi" to the variable x
x = True Assign the boolean value True to the variable x
type(x) Get the data type of variable x
int(x), float(x), str(x), bool(x) Convert the variable x to an integer, float, string, boolean

Exercises

Exercise: Get the type() of the variable a, defined below.

a = 123
Solution
type(a)
int

Exercise: Get the type() of the variable ok, defined below.

ok = True;
Solution
type(ok)
bool

Exercise: Convert the variable n_trials, defined below, to a float().

n_trials = 13
Solution
float(n_trials)
13.0

Exercise: Convert the variable percent, defined below, to a str().

percent = 0.75
Solution
str(percent)
'0.75'

Exercise: Convert the variable nothing, defined below, to a bool().

nothing = ""
Solution
bool(nothing)
False

Exercise: Assign the boolean value False to a new variable then, convert that variable to an int().

Solution
x = False
int(x)
0

Exercise: Assign the float 0.001 to a new variable then, convert that variable to a str().

Solution
y = 0.001
str(y)
'0.001'

Exercise: Assign the string "Hello" to a new variable then, convert that variable to a bool().

Solution
z = "Hello"
bool(z)
True

Section 2: Performing Operations on Variables

Variables do not store data, they also enable you to perform operations on those data. For this, Python provides a set of builtin operators — special symbols or keywords that perform specific operations. One important class are arithmetic operators, like + and *. In some situations, these behave as you would expect: for example, adding two numbers computes their sum. However, sometimes they do things that may be unexpected: for example, adding two strings concatenates them. Some combinations of data types an operators are not defined at all: for example, you can’t subtract one string from another. Another important class are comparisons such as < or ==. These allow us to ask: is one value greater, smaller or the same as another one, and they always return either True or False. In this section, you’ll learn to apply different operators and how their effect depends on the data type of a variable.

Code Description
x+y,x-y,x/y, x*y Add, subtract, divide, multiply two numbers x and y
x<y, x>y, x==y, x!=y Check whether x is smaller, larger, equal to, not equal to y
x<=y, x>=y Check whether x is smaller than or equal to, larger than or equal to y
"Psycho"+"Py" Concatenate the two strings (result: "PsychoPy")
"pew" * 2 Repeat the string two times (result: "pewpew")
9 ** 2 Square the number 9 (result: 81)
7 % 3 Get the remainder of dividing 7 by 3 (result: 1)

Exercise: What is the sum of the two variables a and b, defined below.

a = 134
b = 4721
Solution
a + b
4855

Exercise: What is the remainder of dividing the variable c, defined below, by 5?

c = 13
Solution
c / 5
2.6

Exercise: What is the square of the variable d, defined below?

d = 567
Solution
d**2
321489

Exercise: Concatenate the strings stored in the variables e and f, defined below.

e = "Hello"
f = "World";
Solution
e + f
'HelloWorld'

Exercise: Divide g by h and assign the result to a new variable. What is the type() of that variable?

g = 6
h = 2
Solution
new = g/h
type(new)
float

Exercise: What is larger? 23 times 81 or 44 squared?

Solution
23 * 81 > 44**2
False

Exercise: Divide 28 by the sum of 3 and 5.

Solution
28 / (3+5)
3.5

Exercise: Repeat the sting, stored in the variable he 10 times.

he = "He";
Solution
he * 10
'HeHeHeHeHeHeHeHeHeHe'

Exercise: Which string value is larger, "a" or "b"?

Solution
"a" > "b"
False

Exercise: Can the avariable N be evenly divided by 3?

N = 35627
Solution
N % 3 == 0
False

Section 3: Storing Multiple Values in Lists

Often, we want to represent not only a single datum but collections of data. The list is a datatype that allows us to do exactly that. Think of lists as a container that can hold any kind of data — even other lists. Since lists are ordered we can also access specific elements of the list by providing their indices. One think to keep in mind is that Python starts to count at 0 so x[0] will return the 1st element of a list and x[1] will actually return the second one.

Code Description
x = [7, 1, 4] Define a list containing three values
[2, 3] + [1] Concatenate two lists (result: (2,3,1))
[1] * 3 Repeat the list (result: [1,1,1])
x[-1] Get the last element of x
x[2:5] Get the 3rd, 4th and 5th element of x
x[1:] Get all elements of x, except the first
x.append(1) Append the number 1 to the list x
len(x) Get the length (i.e. number of elements in) a tuple or list x
sum(x) Get the sum of a tuple or list x

Exercise: Create a list that contains the numbers 1, 2, and 3.

Solution
x = [1, 2, 3]
x
[1, 2, 3]

Exercise: Concatenate the two lists defined below.

weekdays = ["mo", "tue", "wed", "thu", "fr"]
weekend = ["Sa", "Sun"]
Solution
weekdays + weekend
['mo', 'tue', 'wed', 'thu', 'fr', 'Sa', 'Sun']

Exercise: Use the .append() method to add the number 8 to the fibonacci list then, print it.

fibonacci = [0, 1, 1, 2, 3, 5];
Solution
fibonacci.append(8)
fibonacci
[0, 1, 1, 2, 3, 5, 8]

Exercise: Get the len() of the list zeros defined below.

zeros = [0, 0, 0, 0] * 23;
Solution
len(zeros)
92

Exercise: What is the sum() of all elements in the list true_and_false?

true_and_false = [True, False, False, True, True, True]
Solution
sum(true_and_false)
4

Exercise: Get the 3rd element of the dice_numbers list.

dice_numbers = [1, 2, 3, 4, 5, 6];
Solution
dice_numbers[2]
3

Exercise: Get all letters of the alphabet except for "z".

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
Solution
alphabet[:-1]
['a',
 'b',
 'c',
 'd',
 'e',
 'f',
 'g',
 'h',
 'i',
 'j',
 'k',
 'l',
 'm',
 'n',
 'o',
 'p',
 'q',
 'r',
 's',
 't',
 'u',
 'v',
 'w',
 'x',
 'y']

Exercise: Generate a list with 100 zeros.

Solution
[0]*100
[0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0,
 0]

Exercise: Which of the two lists defined below is longer?

k = [1, 2, 3] * 72
l = [4, 5, 6, 7, 8] * 56
Solution
len(k)>len(l)
False

Section 4: Suprises and Pitfalls of Types and Operators

Some combinations of types and operators can produce surprising results. This final section contains some puzzles that ask you to apply operators in different ways and allow you to explore some of the more intricate details of data types and operators. Don’t worry if the results seem confusing at first!

Exercise: Compute the square root of 1156 (Hint: use the ** operator)

Solution
1156 ** -2
7.483147950814765e-07

Exercise: What percentage of Elements in the list below is True?

was_hit = [True, False, True, True, False, False, True, False, False, True, False, False, False, True]
Solution
sum(was_hit)/len(was_hit)
0.42857142857142855

Exercise: Convert the variable False to a str() and then back to a bool()

is_false = False
Solution
bool(str(is_false))
True

Exercise: Is m + n equal to o?

m = 0.1
n = 0.2
o = 0.3
Solution
(m+n) == o
False

Exercise: Extract the integer 1 from the list_of_lists defined below.

list_of_lists = [[[3], [1]], [[2]]]
Solution
list_of_lists[0][1][0]
1