6. Slicing Lists and Strings


#1

I have a question which extends just beyond the material in exercise 6. Slicing Lists and Strings.

What if I want to get at the last two indices of a list of an unknown length?

Thanks for any and all input!


#2

Slicing is from the right, when n is negative, [n:].

Example

print [1,2,3,4,5,6,7,8,9][-2:]     # [8, 9]

#3

like this?

string = "codecademy"
string[-2:] # my


#4

Yes, that's all you need in both strings and lists.


#5

this is all i have and it doesn't work well...

animals = "catdogfrog"
cat  = animals[:3]   # The first three characters of animals
dog  = animals[:4, 5, 6]               # The fourth through sixth characters
frog = animals[:7]              # From the seventh character to the end

#6

There lies the error. Correct instruction is:
dog = animals[3:6] # The fourth through sixth characters

Remember that index starts from 0, not 1. So, the fourth character would be the character at index = 3.


#7

Correct

Incorrect

[start:end]

Think of an interval that is closed on one end, and open on the other. Recall that a closed interval includes its endpoints. '[0,1]' includes both 0 and 1. [0, 1, 2) has the same numbers, excluding the 2.

[3,6)

On the number line this would look like,

0--1--2--(3)--(4)--(5)--6--7 ...

Incorrect will pirint catdogf

The 7th character is at index 6.

[6:]

#8

now I can't do the frog part


#9

it is really weird. I don't really understand this


#10

Use the slice indicated above, [6:].

When the end index is omitted, Python includes everything from that index to the end.


#11

Thank you very much for getting me through this part!


#12

Starting with a string,

animals = "catdogfrog"

We can slice any portion of the string (which goes to a transient copy) in either direction.

The syntax allows up to three parameters. A single parameter with no separator is a plain index, and as such, a slice of a single character at that index.

animals[6]    # f

The parameters are from left to right,

[ start : end : stride ]

Let's look at stride. This is a step value, or constant difference between indices. It has a direction indicated by - if right to left, and no sign if left to right.

 > n = list(0123456789) + ['10']
 > n
=> ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
 > m = n[::2]
 > m
=> ['0', '2', '4', '6', '8', '10']

We need to have both separators in place for Python to know we are referring to a stride in the expression. Above, we counted from 0 to 10 by two's. Because we omitted the index values, Python took it to mean the entire list.

Note that list slicing and string slicing are almost identical. I use a list here so we can use numbers in the demo with relative ease.

 > m = n[::-2]
 > m
=> ['10', '8', '6', '4', '2', '0']

#13

i have it thank you. very much.

frog = animals[6:]

#16