# Python | Sort given list of strings by part of string

• Difficulty Level : Basic
• Last Updated : 11 May, 2020

Given a list of string, the task is to sort the list by part of the string which is separated by some character. In this scenario, we are considering the string to be separated by space, which means it has to be sorted by second part of each string.

Given below are a few methods to solve the given task.

Method #1: Using sort

 `# Python code to demonstrate to sort list ``# containing string by part of string`` ` `# Initialising list``ini_list ``=` `[``"GeeksForGeeks abc"``, ``"manjeet xab"``, ``"akshat bac"``]`` ` `# printing initial list``print` `(``"initial list"``, ``str``(ini_list))`` ` `# code to sort list``ini_list.sort(key ``=` `lambda` `x: x.split()[``1``])``     ` `# printing result``print` `(``"result"``, ``str``(ini_list))`

Output:

```initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
result ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
```

Method #2: Using sorted

 `# Python code to demonstrate to sort list ``# containing string by part of string`` ` `# Initialising list``ini_list ``=` `[``"GeeksForGeeks abc"``, ``"manjeet xab"``, ``"akshat bac"``]`` ` `# printing initial list``print` `(``"initial list"``, ``str``(ini_list))`` ` `# code to sort list``res ``=` `sorted``(ini_list, key ``=` `lambda` `x: x.split()[``1``])``     ` `# printing result``print` `(``"result"``, res)`

Output:

```initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
result ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
```

My Personal Notes arrow_drop_up