iterating list through a function [duplicate] - python

This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 8 months ago.
I have a function that takes a list as parameter (have used a very simple function here to focus on the point of my question).
def some_lst_func(lst):
foo = len(lst)
return foo
lst1= [1, 6, 6, 7, 7, 5]
print(some_lst_func(lst1))
For the whole list this works fine, but I want to incrementally pass the list ([1], [1,6].....) to the function and record each output (i.e. increasing length of list).
Below is what I have tried but is clearly not correct, and not sure what the output is that I am getting, what I would expect is
1
2
3...
for num in lst1:
print(some_lst_func(lst1[:num]))

You need to loop over indices, not items:
def some_lst_func(lst):
return len(lst)
lst1= [1, 6, 6, 7, 7, 5]
for num in range(1, len(lst1) + 1):
print(some_lst_func(lst1[:num]))
# 1
# 2
# 3
# 4
# 5
# 6
# alternatively, using enumerate:
for num, _ in enumerate(lst1, start=1):
print(some_lst_func(lst1[:num]))

Related

Python not iterating over array with for loop [duplicate]

This question already has answers here:
Python invert every two elements of list
(5 answers)
Closed 3 months ago.
Write a program that fills an array of 10 elements with random numbers from 1 to 10, and then swaps the first element with the second, the third with the fourth, and so on. Display the original and transformed array
Here is my solution, but Python doesn't want to sort the array and it stays the same:
from random import randint
numbers = []
for i in range(10):
numbers.append(randint(1, 10))
print(numbers)
a = 0
for a in range(10):
numbers[-1], numbers[i] = numbers[i], numbers[-1]
a = a + 2
print(numbers)
I have tried replacing elements with a loop by numbers[a] = numbers[a+1] , But I kept getting the error:
IndexError: list index out of range
There's a couple things here:
1: as #bereal said, range() has a tird optional step argument, and I've never seen a better time to use it. Check out the documentation for range() https://docs.python.org/3/library/functions.html#func-range
2: I see you reference numbers[-1] even though I think you mean number[-i], it will still reference numbers[-1] on the first iteration, thereby giving an error.
You can make the swap when its not an even number like this:
for a in range(10):
if a % 2 == 1:
tempNumber = numbers[a]
numbers[a] = numbers[a-1]
numbers[a-1] = tempNumber
And then you will have
First output:
[9, 7, 4, 7, 4, 3, 1, 9, 9, 9]
Final output:
[7, 9, 7, 4, 3, 4, 9, 1, 9, 9]

Delete Matching Elements in two Arrays - Python [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 3 years ago.
def array_diff(a, b):
b_index=0
while b_index < len(b):
for x in range(len(a)):
if b[b_index]=a[x]:
del a[x]
b_index+=1
print(a)
array_diff([1,2,3,4,5,6,6,7],[1,3,6])
causes a runtime error because i am mutating the container while still iterating over it
what exactly will be the best practice to delete the matching items and return the list without the items
Initial List [1,2,3,4,5,6,6,7]
Final List [2,4,5,7]
Here is how you can return the result in a new list:
elements = [1, 2, 3, 4, 5, 6, 6, 7]
exclude = [1, 3, 6]
result = [e for e in elements if e not in exclude]
# result == [2, 4, 5, 7]

Issue removing duplicates from list [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 3 years ago.
I am trying to remove duplicate elements from a list. The code is removing the wrong elements.
def simplify(A):
for i in A:
for j in A:
if i == j:
A.remove(j)
return A
Input A:
A = [1, 2, 5, 8, 12, 5]
Output:
A = [2, 8]
Try this.
def RemoveDuplicates(list_):
return list(set(list_))
You can call this function by passing your list and you get back listwithout duplicates.

Iterating over a list and removing elements after comparing them [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I'm trying to iterate over a list of number and removing the values that are lower than a number that I use to compare.
My problem is that there's a number that is lower than the value that I use but it doesnt get removed.
I'm using the remove() function of the list but I don't know why it doesn't get removed
Here is my code:
def remove_lower_numbers(array_numbers, bigger_number):
for elem in array_numbers:
if elem <= bigger_number:
array_numbers.remove(elem)
print(array_numbers)
It works if I used a list comprehension like this:
array_numbers = [x for x in array_numbers if x >= bigger_number]
but I want to do it the way I firts mentioned for learning purposes
I call the function like this:
cards_array = [3, 2, 7]
remove_lower_numbers(cards_array, 8)
but the function prints:
[2]
and 2 is lower than 8 it should return None or a empty list.
Using filter, which keeps only the values that return True for the lambda function:
list(filter(lambda x: x > 3, [1, 2, 3, 4, 5, 2, 3]))
Output:
[4, 5]

Why myList = [range(1,10)] does not return a list in python? [duplicate]

This question already has answers here:
Python range( ) is not giving me a list [duplicate]
(1 answer)
Python 3 turn range to a list
(9 answers)
Closed 5 years ago.
I tried this:
myList = [range(1,10)]
print(myList)
and got this output:
range(1, 10)
why it did not returned a list [1,2,3,4,5,6,7,8,9]?
You are running the example in Python3, where the range function returns an iterable. Therefore, you have to pass the generator to the list function to force the expression to give a full list:
l = list(range(10))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
With a generator, you can iterate over it like so:
for i in function_that_yields_generator():
#do something
You can also use the function next() to get elements from a generator. Since the range function is an iterable not an iterator, you can use this:
l = range(10)
new_l = iter(l)
>>next(new_l)
0
>>next(new_l)
1
>>next(new_l)
2
Etc.
For an iterator, you can do this:
>>s = function_that_yields_generator()
>>next(s)
#someval1
>>next(s)
#someval2

Categories