How do I sort an array in python?
- User
How do I sort an array in python?
Assistant
To sort an array in Python, you can use the built-in
sorted()function. Here is an example:pythonmy_array = [3, 1, 4, 2] sorted_array = sorted(my_array) print(sorted_array) # Output: [1, 2, 3, 4]The
sorted()function takes an iterable (such as a list, tuple, or string) as an argument and returns a new sorted list. The original list is not modified.You can also sort a list in place using the
sort()method:pythonmy_array = [3, 1, 4, 2] my_array.sort() print(my_array) # Output: [1, 2, 3, 4]The
sort()method sorts the list in place, meaning the original list is modified.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.