Manipulating_sequences Flashcards

(8 cards)

1
Q

mutable sequences can be modified how?

A

Replace elements
Delete elements
* often appended (to the end) .append()
* can also specify where in the sequence to .insert

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

Replacing Single Elements

A

Replace an element at index 1 by assigning a new element to that index
l = [10, 20, 30]
l[1] = ‘hello’
l –> [10, ‘hello’, 30]

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

Replacing an entire Slice

A

Just assign a new collection to the slice

my_list = [1, 2, 3, 4, 5]
my_list [0:3] = ['a', 'b']
my_list [0:3] = ('a', 'b')
my_list [0:3] = 'ab'
my_list --> ['a', 'b', 4, 5]

Python uses the elements of the sequence in RHS when assigning to a slice (but not when assigning using a single index)

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

Deleting Elements

A

You can delete an element by index
~~~
my_list = [1, 2, 3, 4, 5]
del my_list[1]
my_list à [1, 3, 4, 5]
~~~

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

Deleting Elements by slice

A

Can delete an entire slice

my_list = [1, 2, 3, 4, 5]
del my_list[1:3]
my_list à [1, 4, 5]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Appending Elements

A

We can append one element

my_list = [1, 2, 3]
my_list.append(4)
my_list à [1, 2, 3, 4]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

To append multiple elements:

A

We extend the sequence

my_list = [1, 2, 3]
my_list.extend(['a', 'b', 'c'])
my_list.extend(('a', 'b', 'c'))
my_list.extend('abc')
my_list --> [1, 2, 3, 'a', 'b', 'c']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Inserting an Element

A

Instead of appending, we can insert at some index
- use sparingly – this is much slower than appending or extending

my_list = [2, 3, 4, 5]
my_list.insert(0, 100)
my_list --> [100, 2, 3, 4, 5]

my_list = [2, 3, 4, 5]
my_list.insert(2, 100)
my_list --> [2, 3, 100, 4, 5]

Element is inserted so its position is the index - remaining elements are shifted right

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