iterating through a list removing items, some items are not removed

2024/11/18 20:29:20

I'm trying to transfer the contents of one list to another, but it's not working and I don't know why not. My code looks like this:

list1 = [1, 2, 3, 4, 5, 6]
list2 = []for item in list1:list2.append(item)list1.remove(item)

But if I run it my output looks like this:

>>> list1
[2, 4, 6]
>>> list2
[1, 3, 5]

My question is threefold, I guess: Why is this happening, how do I make it work, and am I overlooking an incredibly simple solution like a 'move' statement or something?

Answer

The reason is that you're (appending and) removing from the first list whereby it gets smaller. So the iterator stops before the whole list could be walked through.

To achieve what you want, do this:

list1 = [1, 2, 3, 4, 5, 6]
list2 = []# You couldn't just make 'list1_copy = list1',
# because this would just copy (share) the reference.
# (i.e. when you change list1_copy, list1 will also change)# this will make a (new) copy of list1
# so you can happily iterate over it ( without anything getting lost :)
list1_copy = list1[:]for item in list1_copy:list2.append(item)list1.remove(item)

The list1[start:end:step] is the slicing syntax: when you leave start empty it defaults to 0, when you leave end empty it is the highest possible value. So list1[:] means everything in it. (thanks to Wallacoloo)

Like some dudes said, you could also use the extend-method of the list-object to just copy the one list to another, if this was your intention. (But I choosed the way above, because this is near to your approach.)

As you are new to python, I have something for you: Dive Into Python 3 - it's free and easy. - Have fun!

https://en.xdnf.cn/q/71018.html

Related Q&A

Apply function to create string with multiple columns as argument

I have a dataframe like this:name . size . type . av_size_type 0 John . 23 . Qapra . 22 1 Dan . 21 . nukneH . 12 2 Monica . 12 . kahless . 15I wa…

Popping items from a list using a loop in Python [duplicate]

This question already has answers here:Strange result when removing item from a list while iterating over it in Python(12 answers)Closed 3 months ago.Im trying to write a for loop in python to pop out …

Django Admin Media prefix URL issue

i ve the following folder structuresrc\BAT\templates\admin\base.html src\BAT\media\base.css src\BAT\media\admin-media\base.csssettings.pyMEDIA_ROOT = os.path.join( APP_DIR, media ) MEDIA_URL = /media/ …

lazy processpoolexecutor in Python?

I have a large number of tasks that I want to execute and make the results available via a generator. However, using a ProcessPoolExecutor and as_completed will evaluate the results greedily and store …

error occurs when installing cryptography for scrapy in virtualenv on OS X [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Can Python do DI seamlessly without relying on a service locator?

Im coming from the C# world, so my views may be a little skewed. Im looking to do DI in Python, however Im noticing a trend with libraries where they all appear to rely on a service locator. That is, y…

Producing pdf report from python with bullet points

I would like to produce a dynamic pdf document from a python script that looks like the image below. Each sentence starts with a bullet point, and the text and number of lines depends on what the user …

Converting bits to bytes in Python

I am trying to convert a bit string into a byte string, in Python 3.x. In each byte, bits are filled from high order to low order. The last byte is filled with zeros if necessary. The bit string is ini…

Install python package from private pypiserver

I have setup a pypiserver behind an nginx proxy which uses htpasswd for authentication. I am currently able to upload sdists, but I cant figure out how to download them. I want to be able to download t…

Matplotlib Table- Assign different text alignments to different columns

I am creating a two column table and want the text to be as close as possible. How can I specify that the first column be right aligned and the second be left aligned?Ive tried by setting the general …