5. List slicing
slice = letters[1:3] = access a slice of the list
- Sometimes you only want to access a portion of the list
- structure:
- we first create a list called letters
- Then, we take a subsection and store it in the list
slice. We start the index just before the colon and continue up to but not including the index after the colon
- Finally, we print out
['a', 'b', 'c', 'd', 'e'], just to show that we did not modify the original letters list
letters = ['a', 'b', 'c', 'd', 'e']
slice = letters[1:3]
print slice
print letters
7. Maintaining Order: Search and Insert!
my_list.insert(1, "mushroom") = insert mushroom into index 1
my_list.index("grape") = search list for the item "grape"
- Sometimes you want to search for an item in a list
- First we create a list called animals with three strings
- Then, we print the first index that contains the string
"bat" which will print 1
animals = ["ant", "bat", "cat"]
print animals.index("bat")
- We can also insert items into a list
- We insert dog at index 1, which moves everything down
- We print out
["ant", "dog", "bat", "cat"]
animals.insert(1, "dog")
print animals
example: use the .index(item) function to find the index of duck. Then use the .insert(item) function to insert cobra at that index
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck"
animals.insert(duck_index, "cobra")
print animals # Observe what prints after the insert operation
8. For One and All: For-Loops
- If you want to do something with every item in a list you will be happy to know of
for loops.
for every item in this list, do this!
- structure:
for variable in list_name:
# Do stuff!
1. A variable name follows the `for` keyword; it will be assigned the value of each list item in turn
2. Then, `in list_name` designates `list_name` as the list the loop will work on. The line ends with a colon (`:`) and the indented piece of code that follows will be run once per item in the list
- example: Write a statement in the indented part of the
for-loop that prints a number equal to 2 * number for every list item
- Each list item is assigned to the user-defined variable
number in turn
- The for loop will automatically execute your code as many times as there are items in my_list!
``` my_list = [1,9,3,8,5,7]
for number in my_list: # Your code here print 2 * number ```