def second_largest(nums):
    the, sec = 0, 0
    if nums[0] > nums[1]:
        the, sec = nums[0], nums[1]
    else:
        the, sec = nums[1], nums[0]

    for num in nums:
        if num > sec:
            if num >= the:
                the, sec = num, the
            else:
                sec = num
    return sec

This is my code to get second largest element from the list. I assumed that a list has at least two elements. However, it gives me 'gamma' not 'delta' from the input below.

print(second_largest(['alpha', 'gamma','beta','delta']))
    
Well, write your algorithm on paper. What do you get? – cricket_007 50 mins ago
2  
Why not just sorted(['alpha', 'gamma','beta','delta'], reverse=True)[1] ? – zwer 49 mins ago
1  
@zwer: That has worse time and space complexity. – Ryan 48 mins ago
1  
@zwer: Who says it's premature? There's a better-than-even chance that this is a homework assignment with getting O(n) as a goal, anyway. – Ryan 46 mins ago
3  
If we're optimizing with builtins, see heapq.nlargest – roippi 34 mins ago

2 Answers 2

You've initialized the largest and second-largest values to the first two items in the appropriate order, but then you're including them again in the loop. If the largest value was also one of the first two values, it will take up both slots after that point. You can fix it by creating an iterator from the list explicitly and advancing it for the first two elements:

def second_largest(nums):
    it = iter(nums)
    sec, the = sorted((next(it), next(it)))

    for num in it:
        if num > sec:
            if num >= the:
                the, sec = num, the
            else:
                sec = num

    return sec

By not using indexed access, this also has the advantage of working on any iterable.

For real-world use, see heapq.nlargest, which even has specific optimizations in CPython for small numbers of elements.

    
Does this work as intended? second_largest(['alpha', 'gamma','beta','delta', 'echo']) returns echo – cricket_007 36 mins ago
    
@cricket_007: Yeah, because "g" comes after "e". – Ryan 35 mins ago
    
@cricket_007 Yes. echo is correct answer. – Won Kim 35 mins ago
    
Hmm. It's getting late, I guess ;) – cricket_007 34 mins ago

You can try this way:

def second_largest(nums):
    return sorted( nums, reverse=True)[1]

print(second_largest(['alpha', 'gamma','beta','delta'])) # delta
    
Are you sure he can "try this way"? The goal is to solve it in O(n) time, not O(n log n). If you read the comments you'd see he cannot "try this way". – cᴏʟᴅsᴘᴇᴇᴅ 3 mins ago