Python code to Sort Names in Array using Different Methods

There are several ways to sort names in an array in Python. Here are three options that you can learn.

Python code to Sort Names in Array using the sorted function:

names = ["Alice", "Bob", "Charlie", "David", "Eve"]
sorted_names = sorted(names)
print(sorted_names)  # Output: ['Alice', 'Bob', 'Charlie', 'David', 'Eve']

This is the simplest and most efficient way to sort names in an array. The sorted function creates a new sorted list, leaving the original array unmodified.

Python code to Sort Names in Array using the sort method on the original array:

names = ["Alice", "Bob", "Charlie", "David", "Eve"]
names.sort()
print(names)  # Output: ['Alice', 'Bob', 'Charlie', 'David', 'Eve']

This method sorts the original array in-place, meaning it modifies the array directly.

Python code to Sort Names in Array using Custom sorting function with case-insensitivity:

def case_insensitive_sort(names):
  def sort_key(name):
    return name.lower()
  return sorted(names, key=sort_key)

names = ["Alice", "bob", "CHARLIE", "DAVID"]
sorted_names = case_insensitive_sort(names)
print(sorted_names)  # Output: ['Alice', 'bob', 'CHARLIE', 'DAVID']

This option allows you to define a custom sorting function to handle specific logic, such as making the sorting case-insensitive.