Section 08: Lists and Nested Lists Flashcards
Define Lists:
List: contains number of arbitrary ordered elements (values), each of which can be accosiated with an index
- Created w/ square brackets:
[A1, ..., An]
- Index starts from $0$List w/ zero elements:
my_list = []
-
len(my_list)
used to tell how many elements in a list - Any combination of object type:
numbers = [1, "two", 2.22]
Accessing elements in a list
Access using name of list variable and index inside sqaure brackets
- Positive indexing:
my_list[2]
- Negative indexing:
my_list[-1]
- Range of elements:
my_list[2:5]
- Whole list:
my_list[:]
If not element in index[1]
⇒ IndexError
Operators +
and *
in lists:
Concatenate Lists
(1) Concatenate two lists using +
operator:
~~~
»>list1 = [1, 2, 3]
»>list2 = [4, 5, 6]
> > > list3 = list1 + list2
print(list3)
[1, 2, 3, 4, 5, 6]
~~~
(2) Create a new list from an existing list using *
operator: (replicate)
>>>list4 = list1 * 3 >>>print(list4) [1, 2, 3, 1, 2, 3, 1, 2, 3]
in
and not in
in lists
- Test for membership
- Use to test if an object is an element of a list
>>> list5 = [10, 20, 30, 40] #Check if 10 is in list >>> if 10 in list5: print("Yes") Yes #Check if 50 is not in list >>> if 50 not in list5: print("No") No
Good Style:
- Not Good:
if x == 5 or x == 7
- Better:
if x in [5,7]
Two options for
loops for lists?
Option 02:
```python
# Option 01:
def print_list(my_list):
for index in range(len(my_list)): #range(3)
print(“[”, index,”] = “, my_list[index])
for element in my_list:
print(element)
> > > my_list = [4, 6, 19]
print_list(my_list)
[0] = 4
[1] = 6
[2] = 19
~~~
How to modify lists:
- Strings - immutable; lists are not
- Add elements using
append()
andextend()
methods-
append()
adds elements to end of list -
extend()
adds elements of one list to another list -
insert()
adds element at a given index -
remove()
removes element by value -
pop()
removes element by index -
clear()
removes all elements from list -
sort()
sorts list in place (ascending/descending) -
reverse()
reverses order of list in place
-
Erros
TypeError
TypeError if elements are not comparable or right object type
Errors
ValueError
ValueError is raised if no such element
List objects:
-
len(a)
: returns num elements in a lista
-
sum(a)
: returns sum all elemetns ina
(if they are numbers) -
min(a), max(a)
: returns smallest/largest element ina
TypeError if elements are not comparable or right object type -
a.append(x)
adds elements to end of list -
a.extend(x)
adds elements of one list to another list -
a.insert(x)
adds element at a given index -
a.remove(x)
removes element by valueValueError is raised if no such element -
a.pop(i)
: removes and returns the i-th element from the lista
. If no input is specified, the last element is removed and returned. -
a.count(x)
: returns num of occurrences of the element x in lista
-
a.index(x)
: returns index of first occurence of the element x in lista
.ValueError is raised if no such element -
a.sort():
sorts element of the list in a ‘in place’. This means thata
is modified after execution of this method
Common list pattersn
what are common list patterns?
- reducing,
- mapping,
- filtering
Common List Patterns
(1) reducing
Reducing a list to a value
Example: find the sum of all elements in a list
def sum_list(my_list): sum = 0 for element in my_list: sum += element return sum
Common List Patterns
(2) Mapping
Transforming a list to another list; traverse one list while building another ⇒ “map”
Output: new list
Example: double each element in a list
def double_list(my_list): double_list = [] for element in my_list: double_list.append(element * 2) return double_list
Common List Patterns
(3) Filtering
Selecting elements from a list
Output: a new list
Example: select even elements from a list
~~~
def even_list(my_list):
even_list = []
for element in my_list:
if element % 2 == 0:
even_list.append(element)
return even_list
~~~
Altering lists
repeating lists
Repeating Lists:
- Use the
*
operator to duplicate elements
Altering Lists
Comparing Lists
Comparing Lists:
- The
==
operator to each of two lists are equal - Equal if they have same number of elements; elements
- Also use
!=
to check if they are different