LIST METHODS BUILT IN LIST FUNCTIONS LIST METHODS
LIST METHODS BUILT IN LIST FUNCTIONS
LIST METHODS • Built in functions • Allows you to manipulate the data stored in the lists quickly and effectively • Many methods are concerned with finding, adding, and removing pieces of data stored within the list they are being called on. • Others are more concerned with the structure of the list itself.
MAINTAINING ORDER • Sometimes you need to search for an item in a list. • First, we create a list called animals with 3 strings • Then, we print the first index that contains the string “bat”, which will print 1
WE CAN ALSO INSERT ITEMS INTO A LIST • We insert “dog” at index 1, which moves everything down by 1. • Use the . index(item) function to find the index of “duck” • Assign that result to a variable called duck_index • Then. insert(index, item) to the string “cobra” at that index
FOR LOOP • Use if you want to do something with every item in your list • Example: • A variable name follows the for keyword; it will be assigned the value of each list item in turn. • Then in my_list designates my_list as the list the loop will work on. • The line ends with a colon and the indented code that follows it will be executed once per item in the list. • Write a statement so that the indented code prints a number equal to 2*number for every list item.
THE SORT( ) METHOD • If your list is a jumbled mess, you may need to sort() it. • First, create a list called animals with three strings. Make sure the strings are not in alphabetical order. • Then, sort animals into alphabetical order by using the . sort() method. • Then for each item in animals, print each item on their own line.
SORT ( ) METHOD • Note that. sort() modifies the list rather than returning a new list.
APPEND METHOD • A list doesn't have to have a fixed length. • You can add items to the end of a list any time you like!
APPEND VS EXTEND (LISTS ONLY) • append() : used in python to add, one element or object. • extend() : extends list by appending elements from a sequence to the list. Append Extend Code: Gives you:
LIST BUILD UP One common pattern is to start a list a the empty list [], then use append() or extend() to add elements to it:
YOU TRY Write a for-loop that iterates over start_list and. append()s each number squared (x**2) to square_list. Then sort square_list
- Slides: 12