3

I am trying to port some Python code and I am a little lost on small issue which I would appreciate some advice.

I understand the in operator but I am a little unclear on what the : operator does in this example.

if foo in bar[i][:2]:
    # do something

In http://docs.python.org/tutorial/introduction.html#strings it states that the : operator makes the first two characters only if this is a string. However when used with a list like this is that what will happen as well? So does this just mean the first 2 characters of the string in th

baynezy
  • 6,493
  • 10
  • 48
  • 73
  • For a more in-depth understanding of how slices can be used via __getitem__, including Ellipsis, see http://stackoverflow.com/questions/509211/pythons-slice-notation – nealmcb Dec 20 '13 at 01:28

2 Answers2

7

This is called list slicing, you already link to the proper part of the documentation in your question. If you find documentation confusing, there is a video tutorial for that:

http://www.youtube.com/watch?v=iD6a0G8MnjA

vartec
  • 131,205
  • 36
  • 218
  • 244
1

The behaviour of the operator doesn't depend on where its operands come from - it doesn't matter whether it was a literal, a variable, or a complex expression. The operator does its thing because its operand is a string, not because it was computed in a particular way.

Kilian Foth
  • 13,904
  • 5
  • 39
  • 57