Oliver Dungey
Oliver Dungey

Reputation: 39

Python adding an integer to a list

I am trying to add 1 to my variable and then add this variable to a list so when I print out my list, the value of the variable is within it. However, my code prints out an empty list despite me adding the variable to it.

case_number = 0
case_numbers = []

issue = input('Has the issue been solved?').lower()
if issue == 'no':
      case_number += 1
      case_numbers+[int(case_number)]
      print(case_numbers)

Upvotes: 3

Views: 24701

Answers (4)

Mani
Mani

Reputation: 5648

If you want to add a value to a growing list you need to use list.append() method. It adds the value to the end of the list, so you code should be:

case_number = 0
case_numbers = []

issue = input('Has the issue been solved?').lower()
if issue == 'no':
      case_number += 1
      case_numbers.append(int(case_number))
      print(case_numbers)

Extra tip: list.append() method adds value to end of list so if you add the list B into list A using append() then it will add the listB inside the listA like this listA.append(listB)= ["a","b","c",["d","e","f"]] so if you want to add the values as normal list you should use list.extend() method which will add the values of one list to another such that listA.extend(listB)=["a","b","c","d","e","f"]

Upvotes: 2

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

Try using append or insert :

insertis used like the following :

case_numbers.insert(0,case_number) #will insert it at first

or append like this :

case_numbers.append(case_number)

check this link : http://www.thegeekstuff.com/2013/06/python-list/?utm_source=feedly

Upvotes: 0

James Scholes
James Scholes

Reputation: 7906

The issue is with this line:

case_numbers+[int(case_number)]

While it's true that you can append values to a list by adding another list onto the end of it, you then need to assign the result to a variable. The existing list is not modified in-place. Like this:

case_numbers = case_numbers+[int(case_number)]

However, this is far from the best way to go about it. For a start, you don't need to convert your case_number value to an int, because it already is an int. Also, lists have an append method for this exact purpose.

case_numbers.append(case_number)

Upvotes: 0

mahendra kamble
mahendra kamble

Reputation: 1395

if issue == 'no':
      case_number += 1
      case_numbers.append(case_number)
      print(case_numbers)

Here, case_numbers.append(case_number) statements add the elements to the list.

Upvotes: 0

Related Questions