Slicing Lists and Strings


#1


I was testing my codes: -

animal2 = "cat", "dog", "frog"

cat2 = animal2[0:1]
dog2 = animal2[1:2]
frog2= animal2[2]
print cat2
print dog2
print frog2

python console printed these
('cat',)
('dog',)
frog
None

Why was the last one frog, not ('frog') as the others?


#2

You aren't slicing a list. This is a tuple. That's why slicing it returns a tuple.

frog2 isn't same as rest, because you are accessing only one element from animal2 tuple - a string.

In cat2 and dog2 you are slicing tuple, which always return tuple, no matter if you want to get one element or 5 elements.

You can check type by using type() function:

animal2 = "cat", "dog", "frog"

cat2 = animal2[0:1]
dog2 = animal2[1:2]
frog2= animal2[2]
print cat2
print type(cat2)
print dog2
print type(dog2)
print frog2
print type(frog2)

This prints:

('cat',)
<type 'tuple'>
('dog',)
<type 'tuple'>
frog
<type 'str'>

#3

I don't understand.:confused: