Python Forum
output list reducing each time through loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
output list reducing each time through loop
#2
You are getting list of empty lists, not empty list
Output:
[[], [], [], [], []] >>>
Check this link https://nedbatchelder.com/text/names.html
lists are mutable. when you append a to output on line 5, every list you append refers to same elements. when you pop element on line 6 you pop it out from all the lists. To fix this, you need to append copy of a to output
a = [1,2,3,4,5]
output = []
 
while a:
  output.append(a[:])
  a.pop(0)
 
print(output)
Output:
[[1, 2, 3, 4, 5], [2, 3, 4, 5], [3, 4, 5], [4, 5], [5]] >>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: output list reducing each time through loop - by buran - Feb-27-2019, 11:50 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  sum() list from SQLAlchemy output Personne 5 4,583 May-17-2022, 12:25 AM
Last Post: Personne
  Reducing runtime memory usage in Cpython interpreter david_the_graower 2 2,263 Oct-18-2021, 09:56 PM
Last Post: david_the_graower
  Real-Time output of server script on a client script. throwaway34 2 2,099 Oct-03-2021, 09:37 AM
Last Post: ibreeden
  Reducing JSON character count in Python for a Twitter Bot johnmitchell85 2 58,615 Apr-28-2021, 06:08 PM
Last Post: johnmitchell85
  How to measure execution time of a multithread loop spacedog 2 2,927 Apr-24-2021, 07:52 AM
Last Post: spacedog
  Time.sleep: stop appending item to the list if time is early quest 0 1,899 Apr-13-2021, 11:44 AM
Last Post: quest
  concatenating 2 items at a time in a python list K11 3 2,412 Oct-21-2020, 09:34 AM
Last Post: buran
  fraction module: can you stop the reducing? qmfoam 1 2,445 Oct-10-2020, 06:10 PM
Last Post: bowlofred
  using 'while loop' output going into infinite loop... amitkb 2 2,008 Oct-05-2020, 09:18 PM
Last Post: micseydel
  Appending list Trouble Big Time Milfredo 7 3,209 Oct-01-2020, 02:59 AM
Last Post: Milfredo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020