Python Forum
Is there a way to append to a list WITHOUT modifying the parameter passed?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a way to append to a list WITHOUT modifying the parameter passed?
#8
(Sep-17-2018, 10:08 AM)wavic Wrote: If you don't want to modify the original why not tuple?

>>> t = ('one',)
>>> t += ('two',)
>>> t
('one', 'two')
>>> 
Hm! This actually modifies it Confused

No, it creates a new t object

Output:
In [28]: t = ('one',) In [29]: id(t) Out[29]: 140190907161512 In [30]: >>> t += ('two',) In [31]: id(t) Out[31]: 140190903830408
With lists, += will be equivalent to append (or extend)
Output:
In [34]: id(t) Out[34]: 140190903120520 In [35]: t = [1] In [36]: id(t) Out[36]: 140190903091912 In [37]: t += [2] In [38]: id(t) Out[38]: 140190903091912 In [39]: t Out[39]: [1, 2]
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Messages In This Thread
RE: Is there a way to append to a list WITHOUT modifying the parameter passed? - by volcano63 - Sep-17-2018, 10:26 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  append str to list in dataclass flash77 6 571 Mar-14-2024, 06:26 PM
Last Post: flash77
  How to receive two passed cmdline parameters and access them inside a Python script? pstein 2 381 Feb-17-2024, 12:29 PM
Last Post: deanhystad
Question How to append integers from file to list? Milan 8 1,508 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  [ERROR] ParamValidationError: Parameter validation failed: Invalid type for parameter gdbengo 3 11,221 Dec-26-2022, 08:48 AM
Last Post: ibreeden
  read a text file, find all integers, append to list oldtrafford 12 3,707 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  Using .append() with list vs dataframe Mark17 7 10,761 Jun-12-2022, 06:54 PM
Last Post: Mark17
  Modifying code cheburashka 1 1,331 Dec-13-2021, 01:01 PM
Last Post: Kebap
  detecting a generstor passed to a funtion Skaperen 9 3,721 Sep-23-2021, 01:29 AM
Last Post: Skaperen
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 2,366 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  how to modify a variable that is passed as parameter StefanL38 2 2,142 Dec-07-2020, 08:39 AM
Last Post: StefanL38

Forum Jump:

User Panel Messages

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