Lists in Python

Including Cython, Jython, IronPython, PyPy, Django framework, and interpreters: Ipython, IPython Jupyter/Notebook, CPython


Post Reply
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5220
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#1

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] 
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
Post Reply
  • Similar Topics
    Replies
    Views
    Last post

Return to “Python Programming”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 0 guests