Lists in Python
Posted: Mon Aug 29, 2016 2:07 pm
Python stores a list in memory and can use multiple names to refer to the same list, for example
which produces
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 :
The result is then:
- odds = [1, 3, 5, 7]
- primes = odds
- primes += [2]
- print('primes:', primes)
- print('odds:', odds)
Code: Select all
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]
- odds = [1, 3, 5, 7]
- primes = list(odds)
- primes += [2]
- print('primes:', primes)
- print('odds:', odds)
Code: Select all
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7]