+ 2

Why does Python not look at the whole strings(sorted)?

I am trying to solve the google python class exercises. But i am kinda stuck on this one because i dont know why python looks at the characters themselfs and not at the whole string. Can someone tell me why Python looks at the characters and not the strings? # B. front_x # Given a list of strings, return a list with the strings # in sorted order, except group all the strings that begin with 'x' first. # e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] # Hint: this can be done by making 2 lists and sorting each of them # before combining them. def front_x(words): for word in words: if word[0:1] == "x": Liste = [] Liste += word else: Liste2 = [] Liste2 += word return sorted(Liste) + sorted(Liste2) words = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] print(front_x(words)) output : ['a', 'a', 'd', 'n', 'u', 'x', 'a', 'a', 'a', 'd', 'k', 'r', 'r', 'v']

11th Jun 2018, 2:41 PM
Lordi chan
Lordi chan - avatar
2 Respostas
+ 8
Try this: Liste.append(word) And: Liste2.append(word) Where you use +=
11th Jun 2018, 2:51 PM
Paul
Paul - avatar
+ 2
A string is just an array of characters if you think about it. So `Liste = []` will make an empty array and `Liste += word` will add the two arrays together. It's quirky but it is what it is. What you probably want to do is `Liste.append(word)`. I can see another mistake in your code but I hope this brings you a step further :P
11th Jun 2018, 2:56 PM
Schindlabua
Schindlabua - avatar