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)
4 Answers 4
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"]
Comments
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.
Comments
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)
Comments
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
+creates a new list which you're discarding. What you want iscase_numbers.append(int(case_number))case_numbers+=[int(case_number)]case_numbers+=[int(case_number)](forgot the equal)case_numbers.append(...).case_numbers.append(int(case_number))is the standard way. The reason your approach doesn't change the list is that you don't assign the modified list back tocase_numberse.g.case_numbers = case_numbers + [int(case_number)]