Python Basics Flashcards

1
Q

Two ways of creating an empty list.

A
empty_list = []
empty_list = list()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Format for accessing an element in a list by indexing?

A

listname[index_number]

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

How can a matrix be represented in a list.

A

By nesting the list:

B = [ [ 1, 2 ], [ 0 ,4 ] ]

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

Format for slicing a list?

Which items get included?

A

mylist[ 0 : 3 ]
0, 1, 2
(Not inclusive of last index)

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

What is the format for slicing a list to the end or from the beginning?

A

to end -> mylist[ 2 : ]

from beginning -> mylist[ : 5 ]

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

Format and function of using the step feature when list slicing?

A

myList[ 1::2 ] - goes to end of list, returning every other element
myList[ 1::3 ] - goes to end of list, returning every third element

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

Format for returning the index of an item in a list?

A

myList.index(element_name)

Returns first occurence.

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

Options for adding items to a list?

A
new_list = myList.append( new_element )
new_list = myList + [ new_element ]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Format for sorting a list in place and non-muted?

A

sorted( myList ) - non-muted

myList.sort() - in place

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

Format of dictionaries?

A

dictname = {key1:value1, key2:,value2, …}

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

Two things to keep in mind about dictionaries?

A

They are unordered.

The keys must be unique.

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

Format to access the value of a given key?

A

myDict[ key_name ]

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

How to get list of keys from a dictionary?

A

myDict.keys( )

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

How to get a list of values from a dictionary?

A

myDict.values( )

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

How to sort a dictionary by the keys?

A

sorted( myDict )

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

How to sort a dictionary by the values?

A

sorted( myDict.values( ) )

17
Q

Format of for loop?

A

for i in my_str:

18
Q

Three ways to do string interpolation (formatting) in python?

A

1 - Do NOT use
name = “Eric”
“Hello, %s.” name

2 - Can use
name = “Eric”
“Hello, { 1 }”.format( name )

3 - Do use
name = “Eric”
f”Hello, { name }.”