Python, Having problems with .append() method [duplicate] - python

This question already has answers here:
How to modify list entries during for loop?
(10 answers)
Closed 5 years ago.
I'm using anaconda Python 3 notebook. And When I Try to append anything to a list, my pc goes mad. It gets slow, the RAM goes to 95% and it just wont work anymore. But i noticed somethin, the problem only occurs when I use a for statement. and if I use slice brackets I dont have that problem, so thi would be like this:
Problem:
for element in anylist:
anylist.append('whatever')
(So far, i think this one never stop working and it may be causing some truobles. I dont really know)
No problem:
for element in anylist[:]:
anylist.append('whatever')
Another detail: All this started right before I imported the String module, and the Os module. But now it happens every time i write single code.
Python is in 64 bits as it has to be in my case.
If you could help me I would appreciate it.

The first example can be translated as:
while there is something more in anylist add whatever to the end
which means the list will grow until the system crashes.
So it will never end. The second translates as:
for the number of items in anylist add whatever to the end of the list.
So will double the length of the list.
Hence python is doing exactly what you are telling it to do, (which I suspect is not what you think you are doing).

Try doing:
for element in range(len(anylist)):
anylist.append('something')

Related

Can you please explain me this for loop of a python quiz question? [duplicate]

This question already has answers here:
Behaviour of increment and decrement operators in Python
(11 answers)
Closed 1 year ago.
I was surfing YouTube and found a random video of a python quiz. The question goes like this:
What will be the output of this python code:
a = []
for i in range(10):
a.append(i * ++i)
for a[i] in a:
print(a[i])
I paused the video, tried to figure out the output, but I couldn't, because python doesn't have any ++ operator. Then I continued the video and I understood the first for loop, but the second for loop is very tricky, as is mentioned in the video. The guy explained in the video what is happening in the second for loop, but the explanation was too brief for me to understand it clearly. I tried to run the code in VS code, trying print statements and other stuff but still no help.
So, can you please help me in understanding the second for loop, maybe a step-by-step explanation?
Here's the video link (Hindi language): https://youtu.be/HbjaAm4Bib0
You can run it to see the output. The code is misleading and error prone (was that a quiz on bad practices?) .
The i * ++i part seems to suggest some special additive process for the ++i but ++ is not an operator in Python and it is simply interpreted as indicating that the sign of i is unchanged twice (in short, ++ does nothing here so the code is equivalent to i*i)
The for a[i] in a: part is really bad. It uses the residual value of i (which is the last index of a in this case) and makes that item in a the iteration variable for the loop. This means that at every iteration, the last item in a will be assigned with the current item value. This will cause the last value printed to be the same as the one-before-last (thus losing the last value in a)

Writing million digits of pi in an array. Output : "<map object at 0x0000000005748EB8>" [duplicate]

This question already has answers here:
Getting a map() to return a list in Python 3.x
(11 answers)
Closed 2 years ago.
I was trying to write a million digits of pi in an array with each digit as an individual element of the array. The values are loaded from a '.txt' file from my computer. I have seen a similar question here. Written by the help of this, my code is:
import numpy as np
data = np.loadtxt('pi.txt')
print(map(int, str(data)))
But the output is this:
<map object at 0x0000000005748EB8>
Process finished with exit code 0
What does it mean?
A few operations with Python version 3 become "lazy" and for example mapping now doesn't return a list of values but a generator that will compute the values when you iterate over it.
A simple solution is changing the code to
print(list(map(int, str(data))))
This is quite a big semantic change and of course the automatic 2->3 migration tool takes care of it... if you programmed in Python 2 for a while however is something that will keep biting you for quite some time.
I'm not sure about why this change was considered a good idea.
map in Python 3 will give you a generator, not a list, but in python 2 it will give a list.
The stack overflow link you have given refers to Python 2 where as you are writing code in python 3.
you can refer to these ideone links.
python 2 https://ideone.com/aAhvLD
python 3 https://ideone.com/MjA5nj
so if you want to print list you can do
print(list(map(int, str(data))))

loop a list - length of list but do not need the item created, pythonic? [duplicate]

This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 4 years ago.
This is going to be a bit silly of a question. I have a simple list:
my_list = ["apple", "orange", "car"]
And I'd like to run a loop for the length of that list, but I don't need anything in the list. I can clearly do this:
for item in my_list:
call_external_thingy()
Which would loop 3 times, perfect. However, I'm never using the item in my for loop. So while this does work, everytime I look at my code I feel that I've made a mistake, "Oh shoot, I didn't pass item in.. oh right I just need to run that command for the number of items in the list..."
What would be the more pythonic way to simply run a for loop for the number of items in a list without creating item. I'm thinking of something with len or range but can't get my head around it and anything I mock up just looks like a big mess.
Note, I'm tempted to put this on codereview instead, but they usually want all the code and a lot of why. This seems like a simple enough question to be here, but I could be wrong!
Thank you!
This is pythonic :
for _ in my_list:
call_external_thingy()
for i in range(len(my_list)):
call_external_thingy()

Python - attempting to make a morse code LED [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
i have attempted to write the code such that it will tell you to input your string. at which point you type a string for example lets say you type "purple" then press enter. the code will run and get the length, then instead of getting the first letter variable[0] as P and then lighting the LED in the code for P, it constantly interprets all letters as A. i know its going to be something small but ive only been learning python for a few days so try to be nice. i have previous experience with VB so i have most likely used the wrong syntax somewhere but i cant figure it out. PLEASE HELP.
i cant copy the code into this without rewriting it so im going to use screenshot links.
this is where i think the problem must be
http://puu.sh/lUf9q/3ad50c4faf.png
and then this is how i've set the morse code patterns
http://puu.sh/lUfgo/f6f3f2cb32.png
the reason there is 2 = and 1 == is because i was tinkering with them to see if they were the problem which they aren't
Thanks in advance
EDIT:
apparently i have to edit it to say why its different to said thread. The way its different is: its not but I didn't realise that the problem in the thread was the problem i was having.
It is interpreting all letters as "a" because your if statement says
if curr = "A" or "a":
In fact == and = are different. One does assignment, and the other checks for equality. This if statement always executes because there is always one side of the or that is true.
Try this instead
if curr.lower() == "a":

Python build a list by two different methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between LIST.append(1) and LIST = LIST + [1] (Python)
I'm new to Python and new to programming. I followed the book ThinkPython and here is one thing I can't get straight.
Exercise 10.7 Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why?
I tried the two methods and found the later one (t=t+[x]) took much longer time than append method. Here is my first question, why would this happen?
I changed the line t=t+[x] to t+=[x] just for no reason only to find this revised version take almost the same time as the append method. I thought t=t+[x] is equal to t+=[x], apparently they are not. Why?
BTW: I tried search Google using python += as key words but it seems Google won't take += as a key word even I put a quotation mark to it.
t = t + [x]
takes t, concatenates with [x] (calling t's method __add__), which creates a new list, which is then named t.
t += [x]
calls the t's method __iadd__ which works directly on the list itself. There is no extra list created.
First, you need to know, that the add method results creating a new object, while append() just modifies the existing object, thus resulting in better performance.
As for the second question, knowing the above, you may find out what the '+=' or 'plus equals' operator is equivalent to in python and therefore behave differently to '+' operator.
You might also want to check out this link which explains the difference between add and iadd methods which are being called in your example and perhaps this one as well to establish your knowledge.

Categories

Resources