1

I'm trying to sort an array into multiple arrays by their starting letter

this is an example

list1 = ["apple", "banana", "carrot", "avocado"]

into this

a = ["apple", "avocado"]
b = ["banana"]
c = ["carrot"]

4 Answers 4

3

As all the answers suggest, it is better to use a dictionary for this instead of making a lot of variables (and easier!). You can make this dictionary by looping over all fruits and add them to the right key (first letter).

list1 = ["apple", "banana", "carrot", "avocado"]

d = {}

for item in list1:
    key = item[0]
    if key in d.keys(): # if key already exists: append to list
        d[key].append(item)
    else: # if key does not exist: make new list
        d[key] = [item]

Output:

{'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['carrot']}

Now you can get all fruits with letter a by doing d['a'].

Sign up to request clarification or add additional context in comments.

Comments

3

Use itertools.groupby

from itertools import groupby
list1 = ["apple", "banana", "carrot", "avocado"]
print([list(val) for _, val in groupby(sorted(list1), key=lambda x: x[0])])
# [['apple', 'avocado'], ['banana'], ['carrot']]
# IF want dictionary 
print({k : list(val) for k, val in groupby(sorted(list1), key=lambda x: x[0])})
# {'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['carrot']}

4 Comments

With this approach it might be hard to later get a list for specific letter.
This is what OP wants a,b,c = [list(val) for _, val in groupby(sorted(list1), key=lambda x: x[0])] which will work for OP
And will not work should you add a single item starting with a different letter. Assigning each of them to a separate variable makes the code very inflexible.
Obviously, but I don't know exactly whats the end goal of OP.
2

It is propably better to save the seperate lists in a dictionary since you don't have to define variables by hand. Like this you can scale the number of elements in the list up.

dic = {}
for elem in list1:
    dic.setdefault(elem[0], []).append(elem)

print(dic)
{'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['carrot']}

Comments

2

It's techincally not sorting, but categorising.

You can use a dictionary keyed by the first letter:

from collections import defaultdict

list1 = ["apple", "banana", "carrot", "avocado"]

d = defaultdict(list)
for el in list1:
    d[el[0]].append(el)

print(dict(d)) # {'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['carrot']}

Resulting dict will contain lists for each letter, e.g d["a"] = ["apple", "avocado"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.