Chapter 4: Variables

Generic badge Open this in Colab

Defining basic variables

In the previous chapters, you’ve already learned how to define your first variables:

# Defining "number" variables:
a = 5
b = 20
c = b/a
print(c)

4.0

# Defining "text" (string) variables:
text_A = "Hello, my name is"
text_B = "Gandalf"
print(text_A, text_B)
print(text_A + " " + text_B) # Alternative expression

Hello, my name is Gandalf
Hello, my name is Gandalf

The following data types are the most common ones in many (scientific) programming languages:

  • integer
  • float
  • complex
  • strings
# most common scientific data types:
integer_number  = 1                # integer numbers
float_number     = 1.0              # floating point numbers
complex_number   = 1 + 2j           # complex numbers
string_1         = "a string"       # strings, defined via '
string_2         = 'also a string'  # strings, defined via "

Note, that you can define strings either via ' or ".

Variable- and filenames

In Python, the following signs are allowed in variable names:

  • capital letters A to Z
  • lowercase letters a to z
  • underscore _
  • numbers 0 to 9 (not in the first place!)

Hence, don’t start a variable name with a number and don’t use special characters. Also, don’t use built-in function names or variables as a variable name (e.g., don’t use print = 7, list = 9, and so forth).

The type command

You can check the data type of any variable by the type(variable) command, e.g.:

print(type(integer_number))
print(type(float_number))
print(type(complex_number))
print(type(string_1))

<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>

Lists

Lists are

  • one-dimensional “arrays” of numbers or strings
  • created with [ … , … , … ]
  • indexing, slicing, adding, replacing and dropping allowed
# number list:
number_list = [33, 37, 38, 39]
print("number list:", number_list)

number list: [33, 37, 38, 39]

# string list:
word_list = ["my", "name", "is", "Gandalf"]
print("word list:", word_list)

word list: ['my', 'name', 'is', 'Gandalf']

# build a list from other pre-defined variables:
a = 7
b = 99
c = a+b
variable_list = [a, b, c, 67]
print("variable list:", variable_list)

variable list: [7, 99, 106, 67]

One often very useful built-in list command is list_variable.append(new entry), which appends new list entries to a pre-defined list:

word_list.append(" and yours?")
print(word_list)

['my', 'name', 'is', 'Gandalf', ' and yours?']

You can also use individual list entries and plug them into another variable:

a = word_list[0]
print(a)

my

Indexing and slicing

Specific elements of any indexable and sliceable variable can be accessed in the following ways:

  • index an element with [], i.e., your_list[index], e.g.,

    print(word_list[0])
    print(word_list[1])
    

    my
    name

  • slice a subset of the list with [start:stop], i.e., your_list[start:stop]

    • leaving start ([:stop]) or stop empty ([start:]) slices from the first or to the last element, respectively.
    • slicing to -1, -2, -3 … means slicing until the penultimate, second to last, third to last .. element.
    print(word_list[0:3])
    

    ['my', 'name', 'is']

    print(word_list[1:])
    

    ['name', 'is', 'Gandalf', ' and yours?']

    print(word_list[:2])
    

    ['my', 'name']

    print(word_list[:]) # similar to print(word_list)
    

    ['my', 'name', 'is', 'Gandalf', ' and yours?']

    print(word_list[0:-1])
    

    ['my', 'name', 'is', 'Gandalf']

    print(word_list[0:-2])
    

    ['my', 'name', 21]

    print(word_list[-2:])
    

    ['Gandalf', ' and yours?']

You can also slice and index by using variables as placeholder, e.g.:

i = 1
j = 4
print(word_list[i])
print(word_list[i:j])

name
['name', 'is', 'Gandalf']

Zero-based indexing: Python uses an index starting at zero and defines intervals as closed on the left and open on the right (i.e., the lower bound is included, but the upper bound is not).

You can also modify (“overwrite”) specific list entries:

word_list[3] = "Arwen"
print(word_list)

['my', 'name', 'is', 'Arwen', ' and yours?']

word_list[2] = 3 * 7
print(word_list)

['my', 'name', 21, 'Arwen', ' and yours?']

The len command

With the len(variable) command you can check the length of any Python array-like variable, e..g.:

print(len(word_list))

5

As with any result, you can plug the output expression into a new variable and re-use it

length_of_word_list = len(word_list)
print(length_of_word_list)
print(length_of_word_list + 4)

5
9

Exercise 1

Please repeat the indexing and slicing commands for number_list = [33, 37, 38, 39]:

  1. Print the first and second list element.
  2. Slice from the first to the second (including) element.
  3. Slice from the second to the last (including) element.
  4. Slice from the first to the last (including) element.
  5. Replace the third element by the number 87.
# Your solution 1.1 here:

Toggle solution 1.1
# Solution 1.1:
number_list = [33, 37, 38, 39]

# Print the first and second list element:
print(number_list[0])
print(number_list[1])

33
37

# Your solution 1.2here:

Toggle solution 1.2
# Solution 1.2:
# Slice from the first to the second (including) element:
print(number_list[0:2])
print(number_list[:2])

[33, 37]
[33, 37]

# Your solution 1.3 here:

Toggle solution 1.3
# Solution 1.3:
# Slice from the second to the last (including) element:
print(number_list[1:])

[37, 38, 39]

# Your solution 1.4 here:

Toggle solution 1.4
# Solution 1.4:
# Slice from the first to the last (including) element:
print(number_list[:])

[33, 37, 38, 39]

# Your solution 1.5 here:

Toggle solution 1.5
# Solution 1.5:
# Replace the third element by the number 87:
number_list[2] = 87
print(number_list)

[33, 37, 87, 39]

Tuples

Tuples are very similar to lists, with the following differences:

  • tuples are created via (..., ..., ...,)
  • tuples are like lists, but not mutable (no adding/appending, replacing and dropping)
tuple_example = (1, 11, 111)
print(tuple_example)

(1, 11, 111)

print(tuple_example[1])

11

… but not mutable”:

tuple_example[1] = 99

TypeError..

Dictionaries

Dictionaries are a bit more structured array-like variables, where the individual indices are assign to a specific key:

  • dictionaries are created via {‘key1': values1, ‘key2': values2, …}
  • value can be any object
  • entries can be indexed via their key
mouse = {'ID': 45768,
         'age': 42,
         'sex': "male",
         'weight': 36,
         'MWM_scores': [59, 50, 40, 27, 14, 11]}
print(mouse)

{'ID': 45768, 'age': 42, 'sex': 'male', 'weight': 36, 'MWM_scores': [59, 50, 40, 27, 14, 11]}

print("mouse's ID:", mouse["ID"])
print("mouse's Age:", mouse["age"])
print("mouse's Morris Water Maze scores:",
      mouse["MWM_scores"])
print("Male or Female?:", mouse["sex"])

mouse's ID: 45768
mouse's Age: 42
mouse's Morris Water Maze scores: [59, 50, 40, 27, 14, 11]
Male or Female?: male

The pprint-command

To print out array-like variables in a more readable, row-like format, you can use the pprint command:

from pprint import pprint as pprint
pprint(mouse)

{'ID': 45768,
` ‘MWM_scores’: [59, 50, 40, 27, 14, 11], ‘age’: 42, ‘sex’: ‘male’, ‘weight’: 36}`

pprint(word_list)

['my', 'name', 21, 'Arwen', ' and yours?']

Changing dictionary entries

Of course you can also add and update dictionary entries:

# Updating/overwriting and existing entry:
mouse["age"] = 99
pprint(mouse)

{'ID': 45768,
` ‘MWM_scores’: [59, 50, 40, 27, 14, 11], ‘age’: 99, ‘sex’: ‘male’, ‘weight’: 36}`

# Adding a new key + entry/value:
mouse["Group"] = "Group A"
pprint(mouse)

{'Group': 'Group A',
` ‘ID’: 45768, ‘MWM_scores’: [59, 50, 40, 27, 14, 11], ‘age’: 99, ‘sex’: ‘male’, ‘weight’: 36}`

Summary: Fundamental data types and structures

  • Lists
    • one-dimensional “arrays” of numbers or strings
    • created with [ ... , ... , ...]
    • indexing, slicing, adding, replacing and dropping allowed
  • Tuples
    • one-dimensional “arrays” of numbers or strings
    • created with ( ... , ... , ...)
    • indexing and slicing possible
    • adding, replacing and dropping not possible
  • Dictionaries
    • dictionaries are created via {‘key1': values1, ‘key2': values2, …}
    • value can be any object
    • entries can be indexed via their key
  • NumPy arrays
    • this we will learn later
  • Pandas DataFrames
    • this we will learn later

Allowed signs in variable names:

  • capital letters A to Z
  • lowercase letters a to z
  • underscore _
  • numbers 0 to 9 (but not in the first place)

updated:

1 other articles are linking to this site