Py Lists (Datacamp + UCSD Wk 2) Flashcards
Assign a value to a variable
eg, x = 5
print values
print()
Exponents in python
base ** exp
find out the type of a variable
type(variable)
concatenate strings
str3 = str1 + str2
convert a string to a float
pi_float = float(“3.14”)
convert int or float to string
str(int_var) or string(numerical value)
can you multiply a string by a number?
Yes. “hey” * 2 = “heyhey”
what are lists?
lists are arrays, and can have have various data types, including other lists
how to assign values to a list
list = [var1, var2, 5, “hello”]
how do you create a 2 dim array with lists
2d = [[“val1”, var1] , [“val2”, var2]]
How do you retrieve individual elements of a list (subset)
list[0] (first element]; list[-1] (last element)
How do you retrieve multiple elements from a list (slice)
list[1:3] - returns elements 1 and 2 (inc start, exc end)
Do you have to specify begin and end of the indices for your list slice?
no. if blank, python will go to end. eg, list[ : 5] will do from begin to 5.
specify elements from n-dim list (eg, 2 dim)
list [1] [2], or list [2] [0:2] - elements 0 to 2 from list 2
how to replace list elements?
x[2:3] = [”s”, “t”]
how to extend a list
list2 = list1 + [“e”, “f”]
remove an element from a list
del( list [1] )»_space; removes element 1, and renumbers all indexed elements after
Point a new list at another list
newList = oldList (points to the same array)
copy the values of a list into a new list (eg, new ind. data structure)
copiedList = oldList[ : ]
append 4 to list [1,2,3] (appends an element to the end. )
list.append(4)
iterate over values in a list
for i in list: print(i)
iterate over list using range
for i in range(0, len(list)): print(list[i])
lists are mutable
you can change the values in the list
Retrieve and delete element with index 2 from a list
list.pop(2)»_space; returns element 2, deletes, and shifts subsequent elements “down” in index
remove an element with the value 33 from a list
list.remove(33)
method to add one list to the end of an other
list.extend(list2)»_space; (appends all the values from second list as values in first list)
iterate through same position in two lists at same time
for x,y in zip(list1, list 2): print(x,” “,y)