Måns Nilsson
Måns Nilsson

Reputation: 451

Unable to change element in list using function

I've tried writing a Python 2 program which uses two classes to create a list of ten elements containing the number 0, and replace the third element in the list with a random number between 1-10. However, when I call and print the add_number_to_list() function, it returns an unchanged list. Here is my code:

#coding: iso-8859-1

import random

class Slumpa:
  def __init__(self):
    pass

  def add_number_to_list(self, list):
    a = random.randint(1, 10)
    list[2] == a
    return list

class Lista:
  def __init__(self):
    self.b = Slumpa()
    self.c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


  def add_number_to_list(self):
        return self.b.add_number_to_list(self.c)


P = Lista()
print P.add_number_to_list()

Also, if you've got a for-loop, like this one:

  for i in range(0, len(lista)):
    if lista[i] == 0:
      lista[i] = a
      break

Do you have to use the break statement in order to get out of the loop, or can you do i = len(lista) + 1?

Upvotes: 1

Views: 119

Answers (2)

thefourtheye
thefourtheye

Reputation: 239463

You are using comparison operator in

list[2] == a

what you need is an assignment operator

list[2] = a

Few suggestions

  1. Never name your variables with the builtin types or function names. In this case list. There is a builtin function with the same name.

  2. Instead of

    self.c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    

    you can do

    self.c = [0] * 10
    
  3. When you are specifying the encoding you can either use

    # coding=<encoding name>
    

    or

    # -*- coding: <encoding name> -*-
    

    but NOT

    #coding: iso-8859-1
    

    check this PEP for the formats supported http://www.python.org/dev/peps/pep-0263/

Upvotes: 4

Alexander Zhukov
Alexander Zhukov

Reputation: 4547

To assign a value to variable, you have to use = , not ==.

Compare

>>>l = [1, 2, 3]
>>>
>>>l[0] == 'foo' # performs a comparison
False
>>>l[0] = 'foo' # assigns value
>>>l
['foo', 2, 3]

Upvotes: 1

Related Questions