Search code examples
pythonpython-3.xfunctionlist-comprehension

Problem with sorted phone numbers from hackerrank


I know my attempt is very basic, so is my knowledge of python. the problem asks for getting multiple numbers from user and remove possible 0, +91, or 91 from their left side to make them 10 digit and then sort and print them.

I tried num_list[1] = num_list[1][len(num_list[1])-10:]. It works, so I tried to put it in list comprehension format I'm just studying, but it is not working then. I need help with how to do it hopefully to get a better understanding of when the comprehension format is supposed to be employed.

n = int(input()) # get number of phone numbers from user
num_list = [] # an empty list to store phone numbers in
num_list = [input() for _ in range(n)] # store phone numbers in num_list
##################################
num_list = [num_list[num] = num_list[num][len(num_list[num])-10:] for num in num_list]  #remove  possible 0, +91, 91 from beginning of numbers
########################################
num_list = sorted(num_list)
num_list = ["+91 "+num[:5]+" "+num[5:] for num in num_list]
print(*num_list , sep="\n")

Solution

  • You shouldn't assign directly within a list comprehension.

    The syntax that you're looking for is:

    num_list = [num[-10:] for num in num_list]
    

    which is logically equivalent to:

    cleaned_list = []
    for num in num_list:
        cleaned_list.append(num[-10:])
    num_list = cleaned_list