Chapter 5 - Lists and dictionaries Flashcards
a list method to add something at the end of something else
scores.append(score) - adds score to the end of scores
a list method to remove something based on value (unlike del. which deletes based on position)
scores.remove(score) - removes score
sorts elements in a list (usually in ascending order - smallest values first)
sort()
reverse=True will sort in reverse order
reverse()
reverses the order of a list
count(value)
returns the number of occurrences of value
returns the first position number where value occurs
index(value)
inserts value at position i
insert(value, i)
pop([i])
returns value at position i and removes the value from the list. Providing the position number i is optional. Without it the last element in the list is removed and returned.
removes the first occurrence of value from the list
remove(value)
Name 2-3 reasons to use tuples instead of lists
- Tuples are faster than lists
- Perfect for creating constants
- Sometimes they are required
nested sequences
sequences inside other sequences
>>>name, age = ("Momchil", 21) >>>print(name) Momchil >>>print(age) 21
unpacking (assigning each element to its own variable in a single line of code)
What do variables do?
they are references to values, like a name is a reference to a person (they don’t contain the person)
What is shared referencing?
Several variables referring to the same value (a change in the value results in a change in what all of the variables reference)
What would the string language = “Python” do?
Store the string “Python” in the computer’s memory and then create the variable language, which will refer to that place in the memory
>>> mike = ["khakis", "dress shirt", "jacket"] >>> honey = mike[:] >>> honey[2] = "red sweater" >>> print(honey) ['khakis', 'dress shirt', 'red sweater'] >>> print(mike) ['khakis', 'dress shirt', 'jacket']
honey is assigned a copy of mike. honey does not refer to the same list, instead it refers to a copy. So a change to honey has no effect on mike.
How do dictionaries store information
in items that consists of a key and a value