Python Forum
Help With While Loop and Append
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help With While Loop and Append
#12
(Feb-06-2019, 05:55 AM)laprus Wrote: is there any way where I can transfer only values of nums to other. like only values of one list of numbers to the values of second list of numbers without linkining them. cause I'll be using the main list repeatedly?

In [1]: nums = [1, 2, 3]

In [2]: other = nums[:]        # slice

In [3]: id(nums)
Out[3]: 4384668552

In [4]: id(other)
Out[4]: 4383868296

In [5]: nums.append(4)

In [6]: nums
Out[6]: [1, 2, 3, 4]

In [7]: other
Out[7]: [1, 2, 3]
You should keep in mind that it is only one level deep. Meaning that if list elements are mutable then slice is mutating as well:

In [8]: nums = [[1], [2], [3]]

In [9]: other = nums[:]

In [10]: nums[-1].append(4)

In [11]: nums
Out[11]: [[1], [2], [3, 4]]

In [12]: other
Out[12]: [[1], [2], [3, 4]]
There is of course built-in module copy for deep copies.

For complete picture one additional example of expected behaviour:

In [13]: del nums[-1]       

In [14]: nums
Out[14]: [[1], [2]]

In [15]: other
Out[15]: [[1], [2], [3, 4]]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Help With While Loop and Append - by laprus - Jan-30-2019, 11:02 AM
RE: Help With While Loop and Append - by buran - Jan-30-2019, 12:17 PM
RE: Help With While Loop and Append - by laprus - Jan-31-2019, 05:25 AM
RE: Help With While Loop and Append - by perfringo - Jan-31-2019, 06:49 AM
RE: Help With While Loop and Append - by laprus - Feb-03-2019, 09:19 AM
RE: Help With While Loop and Append - by perfringo - Feb-03-2019, 09:53 AM
RE: Help With While Loop and Append - by buran - Feb-03-2019, 09:59 AM
RE: Help With While Loop and Append - by laprus - Feb-05-2019, 05:09 AM
RE: Help With While Loop and Append - by perfringo - Feb-05-2019, 07:13 AM
RE: Help With While Loop and Append - by buran - Feb-05-2019, 07:49 AM
RE: Help With While Loop and Append - by laprus - Feb-06-2019, 05:55 AM
RE: Help With While Loop and Append - by perfringo - Feb-06-2019, 08:01 AM
RE: Help With While Loop and Append - by laprus - Feb-07-2019, 04:58 AM
RE: Help With While Loop and Append - by perfringo - Feb-07-2019, 07:04 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  why is the append function gets empty on the loop?/python rhai 3 3,248 Jul-07-2018, 12:19 PM
Last Post: rhai

Forum Jump:

User Panel Messages

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