Ch. 3 Flashcards
What is a list?
A collection of items/elements
What is an index?
The position that an element is in within your list, goes from 0 to n-1, where 0 is the first element. To chose the last element or to go from left to right start from -1
How do you change an element in a list?
list_name[index] = “new element” (this will replace the old element with the new one)
What is the simplest way to add a new element to a list?
list_name.append(“element you are adding”) (this adds a new element to the end of the list)
How do you add a new element in a specific position within a list?
list_name.insert(index, “new element”)
How do you remove an element/item from a list using it’s index?
del list_name[index]
What is the pop() Method?
popped_item = list_name.pop(index)
(The pop() Method removes an item in a list, but let’s you work with that item after removing it.)
where, popped_item is the new assignment
NOTE: is you leave the parenthesis blank, it will remove the last item
Why do we use the pop Method?
Sometimes you will want the value of an item after you remove it from a list.
How do you remove an element/item from a list without knowing it’s index and only knowing its value?
list_name.remove(element)
How do you permanently re-sort a list in alphabetical order? In reverse alphabetical order?
list_name.sort()
reverse: list_name.sort(reverse=True)
Remember: everything in lowercase
How do you temporarily re-sort a list in alphabetical order? In reverse alphabetical order?
sorted(list_name)
reverse: sorted(list_name, reverse=True)
How do you reverse a list (permenantly)?
list_name.reverse()
How do you find the length of a list?
len(list_name)
What is an index error?
You indexed past the length of the list