Python Forum
Why doesn't list require global keyword?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why doesn't list require global keyword?
#5
(Jan-15-2024, 01:35 AM)johnywhy Wrote:
(Jan-15-2024, 12:34 AM)sgrey Wrote: if you say x = 101 you cannot modify 0

Unclear. x is mutable. I can say
x+=1
no, what this does is x = x + 1. You are assigning a new value to the variable that overwrites the old one. You cannot change the value that is already assigned to x, you can only assign a new value to it.

Think about it this way: x is a variable, you can change x to anything you want. But the contents of what that variable holds are a different story. You can easier see this with strings.
Say you have s = 'john'. You want to modify it so that the first letter is capital. If it was mutable, you would be able to say s[0] = 'J', and that would work. But you cannot do that because strings are immutable. You can call s[0] and get a 'j' in return, but you cannot assign a new value to it. You have to create a new string "John" and assign it to s. It's the same when you add strings together. If do s += ' Smith', you are not going to get ' Smith' to be appended to the old value. What will happen is python will create a new string in a new memory location for you with the contents 'John Smith', and then assign that new value to s while the old value will be garbage collected later on.

Here, reading material about immutability https://realpython.com/python-mutable-vs...ble-types/
Reply


Messages In This Thread
RE: Why doesn't list require global keyword? - by sgrey - Jan-15-2024, 02:07 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extending list doesn't work as expected mmhmjanssen 2 235 May-09-2024, 05:39 PM
Last Post: Pedroski55
  Find a specific keyword after another keyword and change the output sgtmcc 5 924 Oct-05-2023, 07:41 PM
Last Post: deanhystad
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 1,008 Jun-24-2023, 02:14 PM
Last Post: deanhystad
Question Keyword to build list from list of objects? pfdjhfuys 3 1,654 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  How to make global list inside function CHANKC 6 3,199 Nov-26-2020, 08:05 AM
Last Post: CHANKC
  Pattern Require Last Line Print() why? Harshil 4 2,479 Aug-08-2020, 04:54 PM
Last Post: Harshil
  Require Some Suggestions gouravlal 2 1,924 Jul-27-2020, 06:14 AM
Last Post: gouravlal
  search binary file and list all founded keyword offset Pyguys 4 2,846 Mar-17-2020, 06:46 AM
Last Post: Pyguys
  Where to put the global keyword when assigning variables outside a function? new_to_python 8 3,091 Feb-09-2020, 02:05 PM
Last Post: new_to_python
  Global variable does not seem to be global. Columbo 6 3,779 Jul-15-2019, 11:00 PM
Last Post: Columbo

Forum Jump:

User Panel Messages

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