Sunday, July 23, 2017

List in python – Indexing and Slicing

List in python are sequences. Similar to strings, indexing and slicing work same way for list.
List is zero based index. That means the first index of list starts from ‘0.’

Example:
L1 = [1,2,3,4,5,6,7,8,9,10]
print L1[0] # Accessing the first element of list
>> 1
print L1[9] # Accessing the 10th element of list
>> 10

We can slice list from positions. Always remember that offset starts from zero for list.
Example:
# Slicing list from position
L1 = [1,2,3,4,5,6,7,8,9,10]
print L1[-1] # Negative index -> Starting position from right
>>> 10
print L1[1:5] # Starting from 2nd position (Remember offsets starts from zero) to 4th position(5-1).
>>> [2, 3, 4, 5]

Using slicing technique, you can extract the required elements in list format.
Let say, you have a list which have numeric value starting from 1 to 10 and you want to have sub set of list from the given list which will contain only odd numbers between 1 to 10.

# Slicing techniques
L1 = [1,2,3,4,5,6,7,8,9,10]
print L1[::2] # Skip 1 position from starting index.
>>> [1, 3, 5, 7, 9] # All odd numbers between 1 to 10.

More example on slicing technique:
# Reverse the List
L1 = [1,2,3,4,5,6,7,8,9,10]
print L1[::-1] # Reverse the list element by index.

>>> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

No comments:

Post a Comment