Python Sequences (Indexing and Slicing)

Two main features of a sequence are indexing  and slicing. The former operation allows us to fetch a particular item in the sequence directly and the later operation which allows us to retrieve a slice of the sequence i.e. a part of the sequence.
Using Sequences    

shoplist = [‘john’, ‘marry’, ‘steve’, ‘bruce’]

# Indexing or ‘Subscription’ operation
print ‘Item 0 is’, shoplist[0]
print ‘Item 1 is’, shoplist[1]
print ‘Item 2 is’, shoplist[2]
print ‘Item 3 is’, shoplist[3]
print ‘Item -1 is’, shoplist[-1]
print ‘Item -2 is’, shoplist[-2]

# Slicing on a list
print ‘Item 1 to 3 is’, shoplist[1:3]
print ‘Item 2 to end is’, shoplist[2:]
print ‘Item 1 to -1 is’, shoplist[1:-1]
print ‘Item start to end is’, shoplist[:]

# Slicing on a string
name = ‘slicing’
print ‘characters 1 to 3 is’, name[1:3]
print ‘characters 2 to end is’, name[2:]
print ‘characters 1 to -1 is’, name[1:-1]
print ‘characters start to end is’, name[:]
    
    

Output
    
Item 0 is john
Item 1 is mango
Item 2 is carrot
Item 3 is bruce
Item -1 is bruce
Item -2 is carrot
Item 1 to 3 is [‘marry’, ‘steve’]
Item 2 to end is [‘steve’, ‘bruce’]
Item 1 to -1 is [marry’, ‘steve’]
Item start to end is [‘john’, ‘marry’, ‘steve’, ‘‘bruce’’]
characters 1 to 3 is sl
characters 2 to end is icing
characters 1 to -1 is licin
characters start to end is slicing

Advertisements

One Response to Python Sequences (Indexing and Slicing)

  1. girish says:

    hi
    watch http://www.canaravideo.com which has simmillar topic video clippings

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: