BKDan
BKDan

Reputation: 33

Python: Create a new list of all elements in nested list sorted

applebeesOrders = [
["sangria","dip","quesadilla"],
["salsa","margarita","burger"],
["water", "wings","ribs"]
]

applebeesOrders[0].insert(0, "beer")

print(applebeesOrders)

I am trying to create a list called sortedOrders that will be a copy of my applebeesOrders list that will then be printed in alphabetical order.

Upvotes: 1

Views: 43

Answers (1)

Luan Naufal
Luan Naufal

Reputation: 1424

I didn't quite understand from your question what you want to sort in alphabetical order the list of all items from all the orders, or only the items inside of each order.

In any case, I add the code for both of those options:

1.Sort all items from all orders in a single list

sortedOrders = []
for order in applebeesOrders:
    sortedOrders.extend(order)
print(sorted(sortedOrders))

# Resulting List
# ['beer', 'burger', 'dip', 'margarita', 'quesadilla', 'ribs', 'salsa', 'sangria', 'water', 'wings']


2.Sort all items inside of each order list

sortedOrders = [sorted(order) for order in applebeesOrders]
print(sortedOrders)

# Resulting List
# [['beer', 'dip', 'quesadilla', 'sangria'], ['burger', 'margarita', 'salsa'], ['ribs', 'water', 'wings']]

In case what you want is something different, just let me know so I can update my answer.

Upvotes: 1

Related Questions