Skip to content

Instantly share code, notes, and snippets.

@tom1299
Last active November 21, 2022 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tom1299/ebd55230561ba216918842bbfe51c7df to your computer and use it in GitHub Desktop.
Save tom1299/ebd55230561ba216918842bbfe51c7df to your computer and use it in GitHub Desktop.
A short explanation of python collections and numpy arrays
import numpy as np
# A List is a collection which is ordered and changeable.
# In Python lists are written with square brackets: [1,2,3,4,5]
numbers_as_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# A NumPy array is a collection which is ordered and changeable.
# Numpy arrays must contain elements of the same type.
numbers_as_numpy_array = np.array(numbers_as_list)
# Different behaviour of lists and numpy arrays when multiplying by a scalar
print(numbers_as_list * 2) # Duplicate the list
print(numbers_as_numpy_array * 2) # Multiply each element by 2
numbers_as_list[5] = "5" # This is allowed
numbers_as_numpy_array = np.array(numbers_as_list) # This will fail on the first operation
print(numbers_as_list * 2) # Will work
try:
print(numbers_as_numpy_array * 2) # Will throw an error because of the string
except Exception as e:
print(e)
# Other collections types:
# A tuple is a collection which is ordered and unchangeable.
# In Python tuples are written with round brackets: (1,2,3,4,5)
# A set is a collection which is unordered and unindexed.
# In Python sets are written with curly brackets: {1,2,3,4,5}
# A dictionary is a collection which is unordered, changeable and indexed.
# In Python dictionaries are written with curly brackets, and they have keys and values:
# {"name":"John", "age":36}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment