1

Problem: I would like it to know that the variable in a for loop is a temporary variable? or changing the variable will change the data as well. Since after writing the below code and making changes to 'ele' in the for loop is changing the lists in 'data'.

for ele in data[1:]:
   birthday = ele[2]
   try:
       birthday = birthday.split('-')
       birth_year = birthday[0]
       birth_year = int(birth_year)
   except:
       birth_year = 0
   ele.append(birth_year)
print(data)

Data:

[['last_name', 'first_name', 'birthday', 'gender', 'type', 'state', 'party'],
 ['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration'],
 ['Bland', 'Theodorick', '1742-03-21', '', 'rep', 'VA', ''],
 ['Burke', 'Aedanus', '1743-06-16', '', 'rep', 'SC', ''],
 ['Carroll', 'Daniel', '1730-07-22', 'M', 'rep', 'MD', ''],
 ['Clymer', 'George', '1739-03-16', 'M', 'rep', 'PA', ''],
 ['Contee', 'Benjamin', '', 'M', 'rep', 'MD', ''],
 ['Dalton', 'Tristram', '1738-05-28', '', 'sen', 'MA', 'Pro-Administration'],
 ['Elmer', 'Jonathan', '1745-11-29', 'M', 'sen', 'NJ', 'Pro-Administration'],
 ['Few', 'William', '1748-06-08', 'M', 'sen', 'GA', 'Anti-Administration']]
harmands
  • 1,082
  • 9
  • 24

1 Answers1

0

The for ... in ... loop in python handles variables exactly as a function does.

If every element you are iterating over is an immutable variable such as str or int or float. They can only be changed by reassignment, so nothing is going to change in your original list.

example = [1, 2, 3, 4]
for element in example:
    # We are not changing the element, just reassigning it
    element = 0

print(example)
#: [1, 2, 3, 4]

If the elements are types such as a list or a dict or a class, making changes to them will change the item.

example = [[1, 2, 3], [11, 22, 33]]
for element in example:
    # The element is just a reference to the item inside the list
    #  not a copy. Changing it changes the list
    element[0] = 0
    element.append(9001)

print(example)
#: [[0, 2, 3, 9001], [0, 22, 33, 9001]]

But again, if I was to just reassign the element, nothing changes.

example = [[1, 2, 3], [11, 22, 33]]
for element in example:
    # Again, we are not changing the element, just reassigning it
    element = 0

print(example)
#: [[1, 2, 3], [11, 22, 33]]

Essentially, if you are doing assignment (pretty much anything using the = operator to assign a value), you won't change the original list.

If you're doing anything else (for example calling a function that changes the element like .append() or changing an index or a key), you're modifying the original.


I'd recommend reading up on some of the answers for some questions like this one here: Python functions call by reference. It's not exactly the same thing that you have, but the behavior is the same.

SCB
  • 5,821
  • 1
  • 34
  • 43