Index error:list assignment index out of range - python

I want to:
Take two inputs as integers separated by a space (but in string form).
Club them using A + B.
Convert this A + B to integer using int().
Store this integer value in list C.
My code:
C = list()
for a in range(0, 4):
A, B = input().split()
C[a] = int(A + B)
but it shows:
IndexError: list assignment index out of range
I am unable understand this problem. How is a is going out of the range (it must be starting from 0 ending at 3)?
Why it is showing this error?

Why your error is occurring:
You can only reference an index of a list if it already exists. On the last line of every iteration you are referring to an index that is yet to be created, so for example on the first iteration you are trying to change the index 0, which does not exist as the list is empty at that time. The same occurs for every iteration.
The correct way to add an item to a list is this:
C.append(int(A + B))
Or you could solve a hella lot of lines with an ultra-pythonic list comprehension. This is built on the fact you added to the list in a loop, but this simplifies it as you do not need to assign things explicitly:
C = [sum(int(item) for item in input("Enter two space-separated numbers: ").split()) for i in range(4)]
The above would go in place of all of the code that you posted in your question.

The correct way would be to append the element to your list like this:
C.append(int(A+B))
And don't worry about the indices

Here's a far more pythonic way of writing your code:
c = []
for _ in range(4): # defaults to starting at 0
c.append(sum(int(i) for i in input("Enter two space-separated numbers").split()))
Or a nice little one-liner:
c = [sum(int(i) for i in input("Enter two space-separated numbers").split()) for _ in range(4)]

Related

Display only 1 element when it's a repetition

I would like print a result without duplicate with my multiplication
Here an example :
5*3*2=30
2*3*5=30
5*2*3=30
3*2*5=30
.....
All these element are from my list that I browse and you can see it's always =30
So I would like display only the first element (5*3*2) and not others because they are the same.
To be more accurate, here an example what I have :
list = ['5*3*2','5*2*3','2*3*5','2*5*3']
for i in list:
if eval(i) == eval(i)+1 ??? (I dont know how to say the next element)
print(eval(i))
Thanks for reading
Something like this with not in will help you.
#python 3.5.2
list = ['5*3*2','5*2*3','6*9','2*3*5','2*5*3','8*3','9*6']
elm = []
for i in list:
elm_value = eval(i)
if elm_value not in elm:
elm.append(elm_value)
print(elm)
DEMO: https://rextester.com/QKV22875
The comparison:
eval(i) == eval(i)+1
Will compare if the the number i is equal to i + 1, which will always return False. I'm sure you mean to use i as an index and simply wanted to compare if the current element is equal to the next element in the list. However, doing this doesn't really keep track of duplicates, since you have to consider everything else in the list.
Its also not a good idea to use list as a variable name, since it shadows the builtin function list. Plenty of other suitable names you can use.
One way is to use a set to keep track of what items you have seen, and only print items that you have seen for the first time:
lst = ["5*3*2","5*2*3","2*3*5","2*5*3"]
seen = set()
for exp in lst:
calc = eval(exp)
if calc not in seen:
print(calc)
seen.add(calc)
If you are always dealing with simple multiplying expressions with the * operator(no brackets), you could also use functools.reduce and operator.mul instead to multiply the numbers instead of eval here. This will first split the numbers by *, map each number string to an integer, then multiply every element with each other.
from operator import mul
from functools import reduce
lst = ["5*3*2","5*2*3","2*3*5","2*5*3"]
seen = set()
for exp in lst:
numbers = map(int, exp.split("*"))
calc = reduce(mul, numbers)
if calc not in seen:
print(calc)
seen.add(calc)
Output:
30
With the following list:
l = ['5*3*2','5*2*3','2*3*5','2*5*3', '2*2']
(Note that list is already something in python so I wouldn't recommend using that as a variable name)
I would first create a list of unique values:
unique_vals = set(map(eval, list))
set([4, 30])
Then for each unique values get the first match in l:
[next(x for x in l if eval(x) == i) for i in unique_vals]
I get:
['2*2', '5*3*2']
Is that what you want?

Nested For Loop Copies the last line in set of indicies

for each in Dti:
i = 0
for each in Dti[0]:
xbi[t][i] = Dti[t][i]
print(t)
i = i + 1
t = t + 1
this is just a test that I'm doing to figure out why my complicated code isn't working. I'm trying to iterate through a list and then each value in the list to set a new list of lists equal to that value. I know I could just set them equal to each other, but it needs to be done this way for my more complicated program. Any tips? I'm getting Dti[-1] for each xbi[t]. I've tried with while too and got the same results
Try something like this:
for t, D in enumerate(Dti)
for i, d in enumerate(D):
xbi[t][i] = d
print(t)
You can use slicing in assignments to replace one list's elements with the elements of another list:
for t, row in enumerate(Dti):
xbi[t][:] = row

What does this Python code do? Explanation of brackets

Can you explain these lines?
I can't understand what's happening in brackets (j,pbase).
mults = {}
if c in mults:
(j,pbase) = mults.pop(c)
Unpacking a tuple:
(j,pbase) = mults.pop(c)
Is the same as:
x = mults.pop(c)
j = x[0]
pbase = x[1]
a,b = something
This means something is a sequence of two values. a is assigned to the first value, and b is assigned to the second.
This is called tuple unpacking.
the python .pop() function will remove the item at that index and then return whatever was deleted. this means that the element of mults at index c will be stored within j and pbase. the way this is written would suggest that each element of the list is a tuple or such. this would mean that the first item goes in j and the second in pbase.

How to add values into an empty list from a for loop in python?

The given python code is supposed to accept a number and make a list containing
all odd numbers between 0 and that number
n = int(input('Enter number : '))
i = 0
series = []
while (i <= n):
if (i % 2 != 0):
series += [i]
print('The list of odd numbers :\n')
for num in series:
print(num)
So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.
In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.
One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:
series.append(i)
Good luck with your learning!
Do a list-comprehension taking values out of range based on condition:
n = int(input('Enter number : '))
print([x for x in range(n) if x % 2])
Sample run:
Enter number : 10
[1, 3, 5, 7, 9]

why is it giving index error out of range although i am almost sure I am in range?

i was trying to fill a list with inputs, but it gave me index out of range
although the index is starting from zero, as far as i know we don't have to specify the length of a list in python.
inputs = input("Enter the number of inputs: ")
lists = []
k = 0
while k<inputs:
lists[k]= input()
k+=1
Because you are creating an empty list with lists = [] and then accessing an element of this empty list. This is the cause of the IndexError.
Appending with lists.append() helps you avoid index errors like this one. You generally want to use indexing when accessing elements and not when populating the list.
You can initialize your list before using indexes of it:
lists = [0] * int(inputs)
And then you can use your code
Use list.append() to add an element to the end of the list:
while k<inputs:
lists.append(input())
k+=1
or with a list comprehension:
lists = [input() for _ in range(inputs)]
Another possibility: Initialize lists as an empty list and then append the input with the += operand.
lists = []
k = 0
while k < inputs:
lists += [input()]
k+=1

Categories