Or, in python:
def func(l):
if len(l) == 0:
return []
item = l[0]
if isinstance(item, list):
result = [func(item)]
elif item >= 0:
result = [item ** 2]
else:
result = []
return result + func(l[1: ])
To handle not looping we can use recursion. Since we are already using recursion, we can handle lists with the same recursive function.
test_list = [
[1, 2, 3, -1], 2, 3, [3, -4, 1, 3], -1, -3
]
def positive_square_list(lst, index):
if index < len(lst):
if type(lst[index]) == list:
positive_square_list(lst[index], 0)
index += 1
if lst[index] < 0:
lst.pop(index)
index -= 1
if index == len(lst):
return lst
else:
return positive_square_list(lst, index + 1)
lst[index] = lst[index] ** 2
return positive_square_list(lst, index + 1)
return lst
output = positive_square_list(test_list, 0)
Method #1 : Using list comprehension The combination of above functions can be used to solve this problem. In this, we perform the task of removing negative elements by iteration in one liner using list comprehension ,Sometimes, while working with Python lists, we can have a problem in which we need to remove all the negative elements from list. This kind of problem can have application in many domains such as school programming and web development. Let’s discuss certain ways in which this task can be performed., Method #2 : Using filter() + lambda The combination of above functions can also offer an alternative to this problem. In this, we extend logic of retaining positive formed using lambda function and extended using filter(). ,CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
The original list is: [5, 6, -3, -8, 9, 11, -12, 2] List after filtering: [5, 6, 9, 11, 2]
The original list is: [5, 6, -3, -8, 9, 11, -12, 2] List after filtering: [5, 6, 9, 11, 2]
If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item.,If you’re not sure where the item is in the list, use remove() method to delete it by value.,If you don’t need the removed value, use the del statement.,When you want to insert an item at a specific position in a nested list, use insert() method.
L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h'] print(L[2]) # Prints['cc', 'dd', ['eee', 'fff']] print(L[2][2]) # Prints['eee', 'fff'] print(L[2][2][0]) # Prints eee
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h'] print(L[-3]) # Prints['cc', 'dd', ['eee', 'fff']] print(L[-3][-1]) # Prints['eee', 'fff'] print(L[-3][-1][-2]) # Prints eee
L = ['a', ['bb', 'cc'], 'd'] L[1][1] = 0 print(L) # Prints['a', ['bb', 0], 'd']
L = ['a', ['bb', 'cc'], 'd'] L[1].append('xx') print(L) # Prints['a', ['bb', 'cc', 'xx'], 'd']
L = ['a', ['bb', 'cc'], 'd'] L[1].insert(0, 'xx') print(L) # Prints['a', ['xx', 'bb', 'cc'], 'd']
If an index has a negative value, it counts backward from the end of the list:,If we print nested[3], we get [10, 20]. To extract an element from the nested list, we can proceed in two steps:,A nested list is a list that appears as an element in another list. In this list, the element with index 3 is a nested list:,Although a list can contain another list, the nested list still counts as a single element. The length of this list is 4:
[10, 20, 30, 40]
["spam", "bungee", "swallow"]
["hello", 2.0, 5, [10, 20]]
>>>
if []:
...print 'This is true.'
...
else:
...print 'This is false.'
...
This is false. >>>
>>> vocabulary = ["ameliorate", "castigate", "defenestrate"] >>>
numbers = [17, 123] >>>
empty = [] >>>
print vocabulary, numbers, empty['ameliorate', 'castigate', 'defenestrate'][17, 123][]
>>> print numbers[0]
17
>>> numbers[9-8]
123
>>> numbers[1.0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.,Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.,It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.,As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it, so this example is equivalent to:
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] >>> fruits.count('apple') 2 >>> fruits.count('tangerine') 0 >>> fruits.index('banana') 3 >>> fruits.index('banana', 4) # Find next banana starting a position 4 6 >>> fruits.reverse() >>> fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] >>> fruits.append('grape') >>> fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape'] >>> fruits.sort() >>> fruits['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] >>> fruits.pop() 'pear'
>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack[3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack[3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack[3, 4]
>>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])
>>> squares = [] >>> for x in range(10): ...squares.append(x ** 2) ... >>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = list(map(lambda x: x ** 2, range(10)))
squares = [x ** 2 for x in range(10) ]