Find Second Smallest Element in an Array using Python

Find Second Smallest Element in an Array using Python

Second Smallest Element

In this paragraph today we learn how to find second smallest element in an array with help of Python Programing concept.In Python it does not have arrays, but it has list with the help of using lists it is more easy and comfortable to work with in comparison to arrays.
For Example:
Input : list = [11, 15, 2, 4, 91, 10, 20, 16, 14]
Output :
Second Smallest element is: 4

Working Required for finding second smallest element entered by the user

Step 1: Initialize the array list of element
Step 2: Input the elements from the user
Step 3: Compare it with all other elements entered by the user in the list.
Step 4: When we find desired output
Step 5: Print second smallest number.

Python Code:-

n=int(input("ENTER ARRAY SIZE "))

arr=list()

for i in range(n):

    arr.append(int(input()))

arr=list(set(arr))

arr.sort()

print("SECOND SMALLEST ELEMENT IS ",arr[1])

2 comments on “Find Second Smallest Element in an Array using Python”


  • ena

    mylist=[11, 15, 2, 4, 91, 10, 20, 16, 14]
    mylist.sort()
    print (mylist)

    print[“smallest number is:”,mylist[1])


  • Amulya

    For people who are searching the code in C,
    #include
    void swap(int* xp, int* yp)
    {
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
    }
    int main(void) {
    // your code goes here
    int arr[50]; int n= sizeof(arr)/sizeof(arr[0]); int min_idx;
    printf(“size:\n”);
    scanf(“%d”,&n);
    printf(“arr: \n”);
    for(int i=0;i<n;i++){
    scanf("%d",&arr[i]);
    }
    for(int i=0;i<n;i++){

    min_idx = i;
    for (int j = i + 1; j < n; j++)
    if (arr[j] < arr[min_idx])
    min_idx = j;

    // Swap the found minimum element
    // with the first element
    swap(&arr[min_idx], &arr[i]);
    }

    printf("\n");
    printf("second smallest no: %d",arr[1]);
    return 0;
    }