Chapter 7 - Lists
Chapter 7 - Lists
LIST
A list is an ordered sequence of information, accessible by index
A list is denoted by square brackets, []
A list contains elements
• usually homogeneous (i.e., all integers)
• can contain mixed types (not common)
list elements can be changed so a list is mutable
2
CREATE A LIST
3
CREATE LIST
4
LIST INDICES
5
LIST INDICES
6
INDICES AND ORDERING
7
CHANGING ELEMENTS
8
You can use :
- the concatenation operator + to concatenate two lists.
- the repetition operator * to duplicate elements.
- the slicing operator [ : ] to get a sublist.
- the in and not in operators to check whether an element is
in a list.
You can use a for loop to traverse all elements in a list
You can use the comparison operators to compare the elements of
two lists
9
ITERATING OVER A LIST
10
OPERATIONS ON LISTS
You can use the methods append, extend, insert, pop, and remove to
add and remove elements to and from a list
You can use the index method to get the index of an element in a list,
and the count method to return the count of the element in the list
You can use the sort and reverse methods to sort or reverse the
elements in a list
You can use the split method to split a string into a list
11
OPERATIONS ON LISTS -
ADD
12
OPERATIONS ON LISTS -
ADD
13
OPERATIONS ON LISTS -
REMOVE
14
CONVERT LISTS TO STRINGS
AND BACK
15
OTHER LIST OPERATIONS
1 . You can use the Python built-in functions:
len to return the length of a list.
max to return the maximum elements in a list.
min, to return the minimum elements in a list.
sum to return the sum of all the elements in a list.
2. You can use the shuffle function in the random module to shuffle the
elements in a list
3. You can use the index operator [ ] to reference an individual element in
a list
16
OTHER LIST OPERATIONS
sort() and sorted()
reverse()
and many more! https://docs.python.org/3/tutorial/datastructures.html
L=[9,6,0,3]
sorted(L) returns sorted list, does not mutate L
L.sort() mutates L=[0,3,6,9]
L.reverse() mutates L=[9,6,3,0]
17
ALIASES
18
CLONING A LIST
19
SORTING LISTS
20
LISTS OF LISTS OF LISTS
OF….
21
MUTATION AND ITERATION
TRY THIS IN PYTHON TUTOR!
22
IN-CLASS QUESTIONS
What is the value of L after you run the code below?
L = ["life", "answer", 42, 0]
for thing in L :
if thing == 0 :
L[thing] = "universe"
elif thing == 42:
L[1] = "everything"