Home > Enterprise >  Variable for list index
Variable for list index

Time:12-28

I am a beginner in python and I could really use some help. I'm trying to create a variable to a index for my list. The problem is that the variable becomes the current value in the list not an index. Is there any way I could fix this (without creating a function)?

I would like that the variable 'one' should print '$'

my_list = [1, 2, 3, 4, 5, 6]

one = my_list[0]

print(one)# 1

my_list[0] = '$'

print(one)# it still prints 1

print(type(one)) # <class 'int'>

CodePudding user response:

Your question is a bit unclear, if you want the variable to be the index 0, you could set the variable to 0

one = 0

then access that element at index 0 using that variable

print(my_list[one])

>>>1

which will print the first element in my_list.

However I think what your asking is about why the variable one is not affected when you change the element in my_list

So the problem here is that when you create your variable called one you create a new variable which is a copy of my_list[0].

this means that now you have two separate objects:

  1. one = 1
  2. my_list = [1,2,3,4,5,6]

this means that when you go to change the first element in my_list to '$' it will only affect my_list and the variable one will not be changed, so after doing

my_list[0] = '$'

you will have

  1. one = 1

  2. my_list = ['$',2,3,4,5,6]

so printing the variable one will still print 1.

Since your a beginner I don't think its too important to know exactly why it is like this, but if your interested you can look at this https://www.geeksforgeeks.org/pass-by-reference-vs-value-in-python/ which talks about how variables are created and referenced in python

CodePudding user response:

my_list=[1,2,3,4,5,6]

one=my_list[0]

print(one)

#here one is the old variable. after updating the 0 index, you were still using the old variable.

my_list[0]='$'

print(my_list[0])

output: $

  • Related