0

List.append (x) problem!

hi every one I want to know why this code don't want executed list = [5,3,6,9,7] list_sqr = [] for x in list : list.sort () x = x**2 list_sqr = list.append(x) print (list_sqr) it takes lot of time then error or no results thanx

19th Dec 2016, 8:29 AM
Minovsky
Minovsky - avatar
5 Respostas
+ 4
some changes list = [5,3,6,9,7] list_sqr = [] list.sort () for x in list: x = x**2 list_sqr.append(x) print (list_sqr) list.sort() should execute once only you should append TO list_sqr without assignment to the original list and another word of advice, do not use the word 'list' as a variable name as it is used as a built-in to convert into a list object
19th Dec 2016, 8:46 AM
Burey
Burey - avatar
+ 3
@Rishi Anand way is much more 'pythonian' in its loop approach python provides many 'shortcuts' such as that one for manipulating data (filter, map, reduce, etc....)
19th Dec 2016, 9:01 AM
Burey
Burey - avatar
+ 1
The real power of python lies in exploiting its library. lst = [5,3,6,9,7] lst.sort() lst_sqr = [x**2 for x in lst] print(lst_sqr)
19th Dec 2016, 8:54 AM
Rishi Anand
Rishi Anand - avatar
0
thanks gays I can see clearly now
19th Dec 2016, 9:08 AM
Minovsky
Minovsky - avatar
0
I'm straight... sorry
19th Dec 2016, 9:09 AM
Rishi Anand
Rishi Anand - avatar