Intro to Python for Data Science Flashcards
How do you find the data type of a variable?
type ( var ) will display the datatype of the variable
What is a list? What kind of data types can it contain?
A list is a collection of values.
A list can contain any Python type. Although it’s not really common, a list can also contain a mix of Python types including strings, floats, booleans, etc.
Take this example, where the second and fourth element of a list x are extracted. The strings that result are pasted together using the + operator:
x = [“a”, “b”, “c”, “d”]
print(x[1] + x[3])
How do you replace elements in a list?
Replacing list elements is pretty easy. Simply subset the list and assign new values to the subset. You can select single elements or you can change entire list slices at once.
x = [“a”, “b”, “c”, “d”]
x[1] = “r”
x[2:] = [”s”, “t”]
How do you extend or add elements to a list?
If you can change elements in a list, you sure want to be able to add elements to it, right? You can use the + operator:
x = [“a”, “b”, “c”, “d”]
y = x + [“e”, “f”]
How do you delete elements from a list?
You can also remove elements from your list. You can do this with the del statement:
x = [“a”, “b”, “c”, “d”]
del(x[1])
Pay attention here: as soon as you remove an element from a list, the indexes of the elements that come after the deleted element all change!
How do you get ‘help’ for a certain function?
To get help on the max() function, for example, you can use one of these calls:
help(max)
?max
How can you subset lists and arrays?
To subset both regular Python lists and numpy arrays, you can use square brackets:
x = [4 , 9 , 6, 3, 1]
x[1]
import numpy as np
y = np.array(x)
y[1]