Lists and tuples in python.
Goal: Learn about lists and tuples in python.
mylist = ["a", 1.0, "c", 4]Note that you can mix items of any type in a list. You can also have lists nested inside lists.
my_other_list = ["a", "b", [1,2,3], "d"]The lists are indexed by integers starting with zero. To see the first item in mylist, you would:
firstitem = mylist[0] # returns the item "a"To append new members to the list, the append() method is used as follows:
# To set an item:
mylist[2] = "x" # Changes the item in the index position 2.
print mylist
# Output: ["a", 1.0, "x", 4]
mylist.append("nextitem")
print mylist
# Output: ["a", 1.0, "x", 4, "nextitem"]
Similarly, individual items can be removed from the list using the
remove() method:mylist.remove(1.0)You can also insert items into specific positions:
print mylist
# Output: ["a", "x", 4, "nextitem"]
mylist.insert(1, "inserted_item")Lists can be concatenated by using the "+" operator:
print mylist
# Output: ["a", "inserted_item", "x", 4, "nextitem"]
newlist = mylist + [9, 10, 11]Tuples are very similar to lists and are constructed by using parentheses instead of brackets or just a comma-separated list.
print newlist
# Output: ["a", "inserted_item", "x", 4, "nextitem", 9, 10, 11]
mytuple = (1, 2, -3)Tuples support the same operations as are supported by lists except the appending or modification of elements after they are created. That is, you cannot modify elements or append elements to a tuple.
myvector = (magnitude, direction)
# is the same as
myvector = magnitude, direction
Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple.