Section 08: Lists and Nested Lists Flashcards

1
Q

Define Lists:

A

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]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Accessing elements in a list

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Operators + and * in lists:

A

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]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

in and not in in lists

A
  • 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]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Two options for loops for lists?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to modify lists:

A
  • Strings - immutable; lists are not
  • Add elements using append() and extend() 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Erros

TypeError

A

TypeError if elements are not comparable or right object type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Errors

ValueError

A

ValueError is raised if no such element

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

List objects:

A
  1. len(a): returns num elements in a list a
  2. sum(a): returns sum all elemetns in a (if they are numbers)
  3. min(a), max(a): returns smallest/largest element in aTypeError if elements are not comparable or right object type
  4. a.append(x) adds elements to end of list
  5. a.extend(x) adds elements of one list to another list
  6. a.insert(x) adds element at a given index
  7. a.remove(x) removes element by valueValueError is raised if no such element
  8. a.pop(i) : removes and returns the i-th element from the list a. If no input is specified, the last element is removed and returned.
  9. a.count(x): returns num of occurrences of the element x in list a
  10. a.index(x): returns index of first occurence of the element x in list a.ValueError is raised if no such element
  11. a.sort(): sorts element of the list in a ‘in place’. This means that a is modified after execution of this method
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Common list pattersn

what are common list patterns?

A
  1. reducing,
  2. mapping,
  3. filtering
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Common List Patterns

(1) reducing

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Common List Patterns

(2) Mapping

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Common List Patterns

(3) Filtering

A

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

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Altering lists

repeating lists

A

Repeating Lists:

  • Use the * operator to duplicate elements
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Altering Lists

Comparing Lists

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Altering lists

Adding elements to a list:

A

Adding Elements to a list:

  • Remember strings are immutable - cant change on index leve l
  • Must concatinate:

```jsx
»> x = []
»> x = x + [‘first’]
OR
»> x = []
»> x.append(‘first’)
~~~

17
Q

Define: nested loop

A

Conditional statements: multiple levels of loops

18
Q

Print out a table with rows and columns using a nested loop:

A

```jsx
cols = 12
rows = 12

for j in range(1, rows+1)
for i in range(1, cols+1)
print(j*i, end = ‘\t’)
print(‘——’)
~~~

19
Q

Functions

Purpose of shift_up()

A

voidfunction shift_up() that takes a list as input and modifies it so that all the elem are moved up one position

```python
»> a = [1, 2, 3, 4, 5]
»> shift_up(a)
»> a
[5, 1, 2, 3, 4]
~~~

20
Q

Define nested lists:

A

What if the lists were lists themselves …. ? Nested Lists

Ex: some_numbers = [[1], [1,2,3], [1,2]]

  • Length: 3 (containing lists of integers)
  • First element: list of length 1 …

Lists are mutable

21
Q

Nested lists as matrices

A
  • Use nested lists to represent matrix of numbers
  • Inner lists = one “row” in the matrix

```python
movie_ave = [[81,75,90],
[80, 55, 10],
[40, 90, 99]]

print(movie_ave[1][2]) # Row index and Column index
10
~~~

22
Q

Row-Major Indexing:

Alternative: Column-Major Indexing:

A

```python
for r in range(num_rows):
# Sequence 0 … num of rows - 1
print(‘Printing row”, r)

for c in range(num_cols):
	# Sequence 0 ... num of cols - 1 
	print(r, c, matrix[r][c]) ~~~
23
Q

Column-Major Indexing:

Alternative: Row-Major Indexing

A

```python
for c in range(num_cols):
#Sequence 0 … num of cols - 1
print(‘Printing column,’ c)

for r in range(num_rows): 
	#Sequence 0 ... num rows - 1 
	print(r, c, matrix[r][c]) ~~~
24
Q

How to convert from a list to a string:

A

The join() function:

Join a list of strings into a single string (inverse of split())

  • Can join any iterable (lists, tuples, sets, etc)
list_example = ['hello', 'world']
string_example = ' '.join(list_example)
print(string_example)

Output
hello world

Optional argument called delimiter specifies which character to use to join the elements
~~~
list_example = [‘hello’, ‘world’]
string_example = ‘,’.join(list_example)
print(string_example)

Output
hello,world
~~~

25
Q

How to convert from a string to a list:

A

The list() function:

**********List function breaks a string into individual letters**********

string_example = 'hello world'
list_example = list(string_example)
print(list_example)

Output
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

The split() function:

******Break a string into words******

string_example = 'hello world'
list_example = string_example.split()
print(list_example)

Output
['hello', 'world']
  • Optional argument called delimiter specifies which character to use as word boundaries
    ~~~
    string_example = ‘hello,world’
    list_example = string_example.split(‘,’)
    print(list_example)

Output
[‘hello
world’]
~~~

26
Q

Differentiate between functions and methods:

A

int and round are built in function, get_pseudo is created

> Function: “stand-alone” program that you can call from your program

```python
a = int(‘1234’)
b = round(12.3)
c = get_pseudo()

~~~

> Method Function that “belongs” to an object, call using the dot notation
object.method_name()