Chapter 7 - Lists and Tuples Flashcards
What is a sequence
an object that contains multiple items of data
the items are stored in sequence, one after another
Python provides different types of sequences including lists and tuples. The difference between these:
a list is mutable (changeable)
a tuple is immutable (unchangeable)
What is a list:
an object that contains multiple data items
can hold items of different types
the items are enclosed in brackets and separated by commas
list = [‘item1’,’item2’,’item3’]
The print function can be used to display an entire list
list() function can convert certain types of objects into lists
what is an element
an item stored in a list
format:
list = [‘item1’,’item2’,’item3’]
repetition operator:
makes multiple copies of a list and joins them together.
the * symbol is a repitition operator when applied to a sequence and an integer.
sequence is left operand, number is right
format:
list*n
you can iterate over a list using a for loop
format:
for x in list:
what is an index:
a number specifying the position of an element in a list.
enables access to individual element in list
index of first element in list is 0 and the last is -1
negative indexes identify positions relative to the end of the list.
-1 is the last element of the list, -2 is the second to last, etc.
Do white spaces also take up index positions?
yes
how is an index exception raised
if an invalid index is used
what does the len() function do?
returns the length of a sequence such as a list
example: size = len(my_list)
returns the # of elements in the list, so the index of last element is len(list)-1
can be used to prevent an index error exception when iterating over a list with a loop
LISTS ARE MUTABLE:
what is a mutable sequence
the items in the sequence can be changed
example:
list[1] = new_value
can be used to assign a new value to a list element
concatenation:
joining two things together
+, +=
what is an empty list?
a list that contains no elements
example:
list = []
List slicing
slice:
a span of items that are taken from a sequence
format: list[start:end]
span:
a list containing copies of each element. from start up to, but NOT INCLUDING, end.
if start not specified, 0 is used. if end not specified, len(list) is used for end index
What does this do:
item in list
returns true if item is in the list.
the in operator will help to determine whether an item is contained in a list
similarly you can use not in to see if an item is not in a list
append(item)
used to add items to the end of a list, by modifying the original list