Q.Write a Python statement to perform the following tasks : (USE BUILT_IN FUNCTIONS / METHODS ONLY)
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →To create a new sorted list without altering the original, use sorted(); to check if a character is an alphabet or a number, combine isalpha() and isdigit() with or.
When working with data in Python, two common tasks involve organizing information and validating its type. Python provides powerful built-in functions and methods that allow us to perform these operations efficiently and elegantly, often without needing to write complex custom logic. The key is understanding which tool is appropriate for the specific requirement, especially when constraints like "without modifying the original list" are present.
(i) To create a new list L1 containing the elements of list L arranged in ascending order, without modifying list L.
Sorting is a fundamental operation in computer science, used to arrange elements in a specific order. Python offers two primary ways to sort lists: the sort() method and the sorted() function. The distinction between them is crucial, particularly when the original list must remain unchanged.
list.sort()method: This method sorts the list in-place, meaning it modifies the original list directly and does not return a new list. If you were to assign its result to a variable, you would getNone.sorted()built-in function: This function takes an iterable (like a list, tuple, or string) as an argument and returns a new list containing all items from the iterable in ascending order. The original iterable remains completely untouched. This is precisely what the requirement "without modifying list L" demands.
Therefore, to create a new list L1 with the elements of L sorted in ascending order, while ensuring L itself is not altered, we use the sorted() function.
The sorted() function always returns a new list, leaving the original iterable unchanged. This is a key difference from the list.sort() method, which modifies the list in place.
The Python statement to achieve this is:
L1 = sorted(L)
(ii) A statement to check whether the given character, ch is an alphabet or a number.
Character classification is a common task in programming, often used for input validation, parsing text, or processing user data. Python's string methods provide convenient ways to determine the nature of characters. For a single character ch (which in Python is a string of length 1), we can use specific methods to check if it's an alphabet or a digit. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.