• Slicing an array using Indexing in python technology


    Slicing an array using Indexing in python technology

    Titanium Asked on June 6, 2018 in Python.
    Add Comment
  • 2 Answer(s)
    Best answer

    Python has a slicing feature which allows to access pieces of an array. We, basically, slice an array using a given range (eg. 2nd to 5th position), giving us elements we require. This is done by using indexes separated by a colon [x : y].

    fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
    print(fruits[ : 3])


    ['Banana', 'Mango', 'Grapes']
    ['Apple', 'Banana', 'Mango']
    ['Banana', 'Mango', 'Grapes', 'Orange']
    ['Mango', 'Grapes']

    While creating a slice [1:4], slicing starts (inclusive) with left index number, and slicing ends (exclusive) with right index number. This means slicing only prints out the elements of position 1, 2, and 3. Here, position 4 is exclusive so we don’t get Orange as an output.

    In the code fruits[:3], you can see we didn’t include the index on the left. This means, slicing takes all elements until the index on the right (excluding the right index), i.e. first 3 (0, 1, 2) elements of the array.

    Likewise, fruits[-4:] prints all elements after second position (1 or -4) i.e ‘Banana’. This code is equivalent to fruits[1:].

    In the final code, fruits[-3:-1], it all elements starting from index -3 to -2.

    Titanium Answered on June 6, 2018.
    Add Comment

    Python Array Methods

    Other array operations are also available in Python using list/array methods given as:



    append() to add element to the end of the list
    extend() to extend all elements of a list to the another list
    insert() to insert an element at the another index
    remove() to remove an element from the list
    pop() to remove elements return element at the given index
    clear() to remove all elements from the list
    index() to return the index of the first matched element
    count() to count of number of elements passed as an argument
    sort() to sort the elements in ascending order by default
    reverse() to reverse order element in a list
    copy() to return a copy of elements in a list


    Multidimensional arrays
    All arrays created above are single dimensional. We can also create a multidimensional array in Python. A multidimensional array is an array within an array. This means an array holds different arrays inside it.

    Example 10: Create a two-dimensional array using lists

    multd = [[1,2], [3,4], [5,6], [7,8]]

    When we run the above program, the output will be

    [1, 2]
    [7, 8]
    Titanium Answered on June 6, 2018.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.