Repeat length of list on Python? [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
find the maximum number in a list using a loop
I'm finding the maximum number in a list on Python by using a loop. In order to do that, I need to have a loop where it goes through the entire list. What loop can I use that runs through the entire list? I'm new to Python.

You can go through a list with a for loop like:
for item in lst:
# do something with item
However, an easier way to get the maximum item in a list (which appears to be what you want) is:
max(lst)

Repeating a block of code n times, where n is the length of some_list is done like this:
for i in xrange(len(some_list)):
# block of code
or...
i = 0
while i < len(some_list):
# block of code
i = i + 1

max = None
for e in lst:
if max is None or e > max: max = e
But as David already stated, simply calling max(lst) would do the job.

Related

How to remove same value from one list and how to change ranges automatically [duplicate]

This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 1 year ago.
def my_list(enter_list):
#print(len(enter_list))--> 7 element
for i in range(0, len(enter_list)): # THE PROBLEM IS HERE
count = enter_list.count(enter_list[i])
if count >=2:
enter_list.pop(i)
return enter_list
print(my_list(["purple","coffee",2,6,2,"purple","steak"]))
At first there are 7 value in my list. But after I remove one of the same value from my list , my list's value is decreasing. İf I change the ranges range(0,len(enter_list)-2) like this. It works. I dont know how to change ranges automatically. ( I can change the ranges manually but it'll not work everytime. )
['coffee', 6, 2, 'purple', 'steak']
This is the output when I change the ranges manually.
Rather than attempt to modify the range you are iterating over, I would suggest you create a copy of the enter_list list and pop() the elements out of that list. That way you will be iterating over the full list of items, but you will return the modified version of the list without having to dynamically alter the range of your loop, which I don't believe is possible.
To quickly show the technique in your code:
def my_list(enter_list):
output_list = enter_list.copy()
for i in range(0, len(enter_list)):
count = enter_list.count(enter_list[i])
if count >=2:
output_list.pop(i)
return output_list
Here you return output_list, which will be your filtered version, but by copying the enter_list, you ensure you are iterating over the full set.
Just to add: using pop(i) here will likely result in you popping something out of range near the end of the loop, so this type of loop iterating over the elements might work best:
for items in enter_list:
output_list.pop(item)
Then you ensure you are not going to pop() on an out of range index.
You could do like this:
def my_list(lst):
i = 0
while True:
cnt = lst.count(lst[i])
if cnt > 1:
lst.pop(i)
i += 1
if len(lst) == i:
break
return lst
print(my_list(["purple","coffee",2,6,2,"purple","steak"]))
OUTPUT
['coffee', 6, 2, 'purple', 'steak']
The problem with your approach is that, in the for loop, the len of the list is only evaluated once - at the beginning. The reason why decreasing by 2 makes it work is because there are 2 elements which have one duplicate, so the loop does not go out of range.

For Loop to determine lowest value of a list in python [duplicate]

This question already has answers here:
Can anyone explain me Python for loop (or iteration) algorithm
(4 answers)
Closed 2 years ago.
In the below, I have several questions. Firstly, why do we not define the starting value of i? In WHILE loops I came across this was the case. Secondly, I am finding it difficult to understand the "sequence" of what is happening. I understand that m = L[0] = 1 but the subsequent steps are not clear to me.
L=[1,2,4,-5,7,9,3,2]
m = L[0]
for i in L:
if i<m:
m = i
print(m)
For loops in python are really "for each" loops. Read it as "for each value 'i' in list 'L', do...".
i is not an index, it is the actual element in the list L.
So we set the initial minimum to just the first element of the list, and we say, for each element in our list, if there is a value smaller than our current minimum, we'll set our minimum to that element.
You don't want to define the starting value of i to make the program more variable to other cases. M is going to be the lowest value because that is what we are printing out. So if i is lower than m we want i to be m. The for loop goes through every number in the list.
L=[1,2,4,-5,7,9,3,2]
m = L[0] # start with m as the first value of your list which is 1.
for i in L: # for i in L means for i being consecutively 1 then 2 then 4 then -5 etc...
if i<m: # if i is less than m the starting point, give the value of i to m
# example if m = 1 and i =-3 after this condition m will take the value -3
m = i
print(m) # when you finish looping over all the examples print my m value
I would suggest writing the algorithm on a paper and you will see how easy it is.
m=1
loop
i=1
i<1? No.
go back to loop
i=2
i<1? No.
go back to loop
i=4
i<1? No.
go back to loop
i=-5
i<1? YES.
m = -5
go back to loop
.
.
.
The for loop proceeds via a form of hypothesis testing. First, we establish a loop invariant: something that remains true before and after each iteration. In this case, it is that m is the smallest value in the list that we have seen so far.
When we initialize m = L[0], it is true: having looked only at L[0], m is the smallest value we've seen so far.
Inside the loop, i takes on each value in the list exactly once. We compare it to m, and if i is indeed smaller, we use it as the new value of m. So after each iteration, m remains the smallest value seen so far.
Once the loop completes, having set i to each element in turn, we can conclude that m is not only the smallest value in L that we've seen so far, but it is the smallest value in L, period, because we have looked at every value in L.
The for loop is equivalent to the following while loop:
_index = 0
while True:
try:
i = L[_index]
except IndexError:
break
if i < m:
m = i
_index += 1
As you can see, we initialize _index to 0, and increment it explicitly at the end of each iteration. The for loop essentially keeps track of _index for us. i, on the other hand, is not initialized so much as it is derived from the current values of L and _index.
More generally, for loops don't manage repeated indexing operations, but are based on the iterator protocol. A for loop like
for i in L:
...
is roughly equivalent to
_itr = iter(L)
while True:
try:
i = next(_itr)
except StopIteration:
break
...
There is an easier way to do it without using a for loop so you can run your whatever code you want to run using the min() function for example in here:
L=[1,2,4,-5,7,9,3,2]
print(min(L)
I would recommend using something like this because its easier faster and runs smoother than the code in your question. The code in your question first runs a for loop that gets all the values out of the list and store them as i and runs threw them then it goes to the if statement which checks if the value which is i in this example is smaller than m which has the value of 1 then rewrites the variable m which was the value 1 to the value that is smaller than i which is -5 and as you see there this is a lot of function to run throw and that makes your code slower if the code consist of many lines.(Tip: always try using as minimum for loops or if statements as you can.)
your example:
L=[1,2,4,-5,7,9,3,2]
m = L[0]
for i in L:
if i<m:
m = i
print(m)

Variable in while loop not incrementing after for loops [duplicate]

This question already has answers here:
Appending to list with loop
(2 answers)
Closed 3 years ago.
I am trying to create a cartesian product of the alphabet with loops. I have for loops that create the desired output but i in my while loop is never reached for some reason.
This loop is running forever in a jupyter lab notebook.
lower_az = [chr(ord('a') + i) for i in range(26)]
i=0
n=2
lst = lower_az.copy()
final_list = []
while i < n:
for let in lst:
for j in range(26):
strng = let + lower_az[j]
lst.append(strng)
i += 1
final_list.append(lst)
Unless I am missing something obvious the variable i should increment until it reaches n and stop the while loop at the desired length of strings.
You are changing the list you are iterating over. The problem is not the while-loop, it's the lst.append(strng) while iterating for let in lst.
#blue_note is correct - Python doesn't behave well when you change a list you're iterating over.
It looks like this is just a typo, though: you've got final_list all ready to receive the elements. To fix this, change:
lst.append(strng)
to
final_list.append(strng)
and drop final_list.append(lst) and your program appears to work fine.

Infinite Series in Python [duplicate]

This question already has answers here:
Is there an expression for an infinite iterator?
(7 answers)
Closed 4 years ago.
Is there any function in Python that provides an infinite series similar to generateSequence in Kotlin?
In Kotlin I can do something like:
generateSequence(1) { it + 1 }.take(5).forEach { println(it) }
Obviously this stops with an integer overflow error but I would like to do something similar in Python.
you can write a simple generator
def count(x):
while True:
yield x
x += 1
for i in count(5):
print(i)
of coarse this particular generator is builtin with itertools.count
import itertools
for i in itertools.count(5):
print(i)
Use itertools.count() to get a count object that generates an infinite sequence of values.
You can take the first n items by explicitly retrieving the next item from the count object for the required number of times. Alternatively, and preferably, use itertools.islice() to take the first n items.
Mirroring your example, to take the first 5 values of the sequence using explicit iteration:
from itertools import count
c = count(1) # start from 1 instead of 0
for i in range(5):
print(next(c))
Or using islice():
for n in islice(count(1), 5):
print(n)

Iterating - Python [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 5 years ago.
Trying to remove negative numbers from a list. I kept running into an issue where two successive negative numbers did not get removed. My code is quite simple:
numbers = [-5, 1, -3, -1]
def remove_neg(num_list):
for item in num_list:
if item < 0:
num_list.remove(item)
print(remove_neg(numbers))
#[1, -1]
I found the answer online after trying 4 different versions of my code and pulling a few hairs out of my head. The answer I found assigned r = numbers[:] and then removed items from r instead of the initial list.
def remove_neg(num_list):
r = numbers [:]
for item in num_list:
if item < 0:
r.remove(item)
print(r)
I understand this concept to have two list variables point to separate data. What I don't understand, is why my initial code doesn't work. Shouldn't for i in numbers: iterate through every item in the list? Why would two successive numbers not be treated the same? I've scoured looking for why and can't seem to find an answer.
In the first example you're modifying the list while iterating over it, which, as you've seen, messes up the iteration. While the second example works, it's very inefficient, and it would be much easier to use a list comprehension to construct a new list without the negatives:
def remove_neg(num_list):
return [x for x in num_list if x > 0]

Categories

Resources