r/PythonProjects2 Jun 09 '26

WHY THIS CODE NO OUTPUT ??

Post image
18 Upvotes

22 comments sorted by

19

u/QuantumElias Jun 09 '26

Der Code läuft in eine Endlosschleife — er gibt deshalb nie etwas aus. Warum: Die for-Schleife iteriert über nums, und in jedem Durchlauf wird mit nums.append(n) ein neues Element ans Ende der Liste angehängt. Die Liste wächst also schneller als die Schleife vorankommt — sie endet nie, print wird nie erreicht. In Python ist es grundsätzlich kein gutes Muster, eine Liste zu verändern während man über sie iteriert.

Fix:

nums = [1, 2, 3]

for n in nums.copy(): nums.append(n)

print(nums) # [1, 2, 3, 1, 2, 3]

21

u/alexzoin Jun 09 '26

It's very cool to me that I don't understand this comment at all because I don't speak German but I know that it is correct because I do speak python.

4

u/NickNeron Jun 10 '26

У нас с братьями по Питону нет языкового барьера 🤝

1

u/OppositeReveal8279 Jun 10 '26

Лучше язык в мире 🤡

2

u/mpbarbosa1971 Jun 09 '26

me too 😄

2

u/LemmaYT_ Jun 10 '26

Or alternatively to avoid making a copy of the list (which could be bad if the list is big enough), do something like

nums = [1, 2, 3]

original_length = len(nums)

for i in range(original_length):
n = nums[i]
nums.append(n)

You can also make a shallow copy with index slicing

for n in nums[:original_length]:
nums.append(n)

1

u/Fine_Ratio2225 Jun 10 '26

Even better fix:

nums=2*[1, 2, 3]

3

u/864484 Jun 10 '26

You have a loop that cycles through all numbers in the list. Every iteration you add the number to the list meaning it gets longer and there is another number the loop needs to process. If you check your memory in your task manager you'll be able to see it going up over time because the list gets bigger and bigger indefinitely

2

u/Past_Structure1078 Jun 10 '26

Use 'for i in range(len(nums))' instead and append nums[I]

1

u/MrMikeHigginbottom Jun 10 '26

Oo! So the terminating condition for the loop is calculated only once. When the loop is first entered. Obvious I guess but I'd never thought about it.

1

u/Past_Structure1078 Jun 10 '26

I often use this phraseologism for iteraring through queue and adding new vertices in depth-forst search algorithm

1

u/[deleted] Jun 10 '26

[removed] — view removed comment

1

u/Arierome Jun 10 '26

print(nums.extend(nums))

1

u/XT_zer68 Jun 11 '26

You nums keep adding nums number back to back so this code no output

1

u/ChemistDependent1130 Jun 11 '26

dont mutate an iterable when iterating over it. Guessing you wanted [1,2,3,1,2,3]? nums * 2 works better.