Page 1 of 1

Lists in Python

Posted: Mon Aug 29, 2016 2:07 pm
by Eli
Python stores a list in memory and can use multiple names to refer to the same list, for example
  1. odds = [1, 3, 5, 7]
  2. primes = odds
  3. primes += [2]
  4. print('primes:', primes)
  5. print('odds:', odds)

which produces

Code: Select all

primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]
 
If you want to copy a list and then modify it, simply use a list function to avoid modifying a list you do not mean to :
  1. odds = [1, 3, 5, 7]
  2. primes = list(odds)
  3. primes += [2]
  4. print('primes:', primes)
  5. print('odds:', odds)

The result is then:

Code: Select all

 primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7]