Asked  7 Months ago    Answers:  5   Viewed   21 times

I've got a list that I create a copy of in order to do some manipulations while still keeping the original list. However, when I set copy_list equal to org_list, they become the same thing, and if I change copy_list, org_list changes too. For example:

org_list = ['y', 'c', 'gdp', 'cap']

copy_list = org_list

copy_list.append('hum')

print(copy_list)
print(org_list)

returns

['y', 'c', 'gdp', 'cap', 'hum']
['y', 'c', 'gdp', 'cap', 'hum']

I don't know too much about what is actually going on but it looks like org_list is actually passing itself to copy_list so that they are actually the same thing.

Is there a way to make an independent copy of org_list without doing something clumsy like:

copy_list = []
for i in org_list:
    copy_list.append(i)

I say this because I have the same problem with other types of variables, for example a pandas dataframe.

 Answers

99

That is because in python setting a variable actually sets a reference to the variable. Almost every person learning python encounters this at some point. The solution is simply to copy the list:

copy_list = org_list[:] 
Tuesday, June 1, 2021
 
Pwner
answered 7 Months ago
27

python3 is not Python syntax, it is the Python binary itself, the thing you run to get to the interactive interpreter.

You are confusing the command line with the Python prompt. Open a console (Windows) or terminal (Linux, Mac), the same place you'd use dir or ls to explore your filesystem from the command line.

If you are typing at a >>> or In [number]: prompt you are in the wrong place, that's the Python interpreter itself and it only takes Python syntax. If you started the Python prompt from a command line, exit at this point and go back to the command line. If you started the interpreter from IDLE or in an IDE, then you need to open a terminal or console as a separate program.

Other programs that people often confuse for Python syntax; each of these is actually a program to run in your command prompt:

  • python, python2.7, python3.5, etc.
  • pip or pip3
  • virtualenv
  • ipython
  • easy_install
  • django-admin
  • conda
  • flask
  • scrapy
  • setup.py -- this is a script you need to run with python setup.py [...].
  • Any of the above together with sudo.

with many more variations possible depending on what tools and libraries you have installed and what you are trying to do.

If given arguments, you'll get a SyntaxError exception instead, but the underlying cause is the same:

>>> pip install foobar
  File "<stdin>", line 1
    pip install foobar
              ^
SyntaxError: invalid syntax
Tuesday, June 1, 2021
 
QuantumMechanic
answered 7 Months ago
51

Use a dictionary:

>>> data = [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
>>> result = {}
>>> for card, value in data:
        total = result.get(card, 0) + value
        result[card] = total

    
>>> print result.items()
[('Visa': 1195.5), ('Rogers': 61.5)]
Saturday, August 7, 2021
 
Nickool
answered 4 Months ago
58

use the following to convert to a timestamp in python 2

int((mod_time.mktime(first_run.timetuple())+first_run.microsecond/1000000.0))

Sunday, August 22, 2021
 
waylaidwanderer
answered 4 Months ago
69

This is how to perform a deep copy for a list has sub-list, thanks moneer alhashim, your answer guided me.

I'm posting it as an answer to help someone else find the solution easy.

So, the key here is to map the original list types.map(...) and fill it manually instead of using List.from(), and that will create a new instance for deep objects.

First, i declared one function for each list:

//For the parent list:

List<Types> getNewTypesInstance {
    // This function allows to perform a deep copy for the list.
    return types.map((e) =>
        Type(id: e.id, title: e.title, subTypes: e.subTypes))
        .toList();
}


// For the child list:

List<SubType> getNewSubTypesInstance(List<SubType> lst) {
    // This function allows to perform a deep copy for the list:
    return lst.map((e) =>
        SubType(id: e.id, title: e.title))
        .toList();
}

And if you have more deep list(s), you will need third function to obtain it as new instance and so on.

Finally, the way how to call them is to write this code within setState():

_filteredTypes = getNewTypesInstance

for(var i = 0; i < _filteredTypes.length; i++) {
    // This is where i filter the search result when a subType.title matches the search query:
    _filteredTypes[i].subTypes = List.from(getNewSubTypesInstance(_types[i].subTypes!.where((element) => element.title.toLowerCase().contains(query!.toLowerCase())).toList()));
}

// This is where i filter the search result and remove any type doesn't match any subType.title:
_filteredTypes.removeWhere((element) => element.subTypes!.length == 0);

bindTypes(); // To refresh the list widget
Thursday, December 2, 2021
 
McDowell
answered 2 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share