Module 6: Flashcards
list
a container that stores a sequence of values
square brackets indicate that we are creating a list.
values = example: [1,2,3,4,5,6]
How can you get the length of a list?
len()
How can you get the number of a specific number of the list?
get the index
example:
values[n]
How can you set a specific element of a list to another integer?
Example:
values[2] = 15
sets the 3rd integer to a value of 15
Does a integer list start at 0 or 1 for a list?
0
How do negative values react with lists?
negative subscripts provide access to the list elements in reverse order
example:
#sets the last element to 20
scores[len(scores) -1] = 20
How can a new element be appended to the end of a list?
with the append method
example:
friends.append(“Harry”)
How can you insert OR change an element in a list with a specific position?
with the insert method OR using brakets ~
example:
friends.insert(1, “Cindy”)
OR
friends[1] = “Cindy”
“Cindy” will be inserted in position 1 HOWEVER, brackets will change the variable entirely not inserting it
How can you test if an element is present in a list?
Use an in operator:
if “Cindy” in friends:
print(“She’s a friend”)
How do you find the position at which an element occurs?
Will set n to the position at which Emily is at
the index method:
n = friends.index(“Emily”)
HOWEVER index only finds the first occurrence if it is in the list multiple times.
If a second argument is passed to the index method, its value indicates the starting position in the list where the search begins
Whats the main difference between lists and strings?
They are both sequences, but lists can hold values of any type, whereas strings are sequences of characters. Strings are also immutable (meaning you cannot change the characters in the sequence), whereas, lists are mutable.
Concatenation of lists and example
you can do this with +
example:
myNumbers = [6,7,8]
yourNumbers = [3, 4 5]
ourNumbers = myNumbers+yourNumbers
#Sets ourNumbers to [6,7,8,3,4,5]
replication
replication of two list uses the “*” operator
numbers = [1,2,3]*3
#Sets numbers to [1,2,3,1,2,3,1,2,3]
equality and inequality testing
You can use the == operator to compare whether two lists have the
same elements, in the same order.
[1, 4, 9] == [1, 4, 9] # True
[1, 4, 9 ] == [4, 1, 9] # False.
The opposite of == is !=
[1, 4, 9] != [4, 9] # True.
Sum, Maximum, Minimum
If you have a list of numbers, the sum() function yields the sum of all values in the list.
sum([1, 4, 9, 16]) # Yields 30
For a list of numbers or strings, the max() and min() functions return the largest and smallest value:
max([1, 16, 9, 4]) # Yields 16
min(“Fred”, “Ann”, “Sue”) # Yields “Ann”