Trying to assign 2-D array of size 6 - python

for i in xrange(6):
arr[i]=map(int,raw_input().strip().split())
it is showing
IndexError: list assignment index out of range

You could use a list comprehension to do it:
arr = [map(int, raw_input("enter values for row %d: " % i).strip().split())
for i in xrange(6)]
print arr

You have two problems :
First, you do not initialize the list before using it. Thus, arr is used as a list, even though it may have been created as another type of variable.
Second, you want to change the value for index i when there is no value for this index.
You can either create a list of six elements beforehand : arr = [ 0,0,0,0,0,0] or you can add the elements to the list as you create them : for i in xrange(6): arr.append(map(int,raw_input().strip().split()))
I do not know if it possible to create a list of a given size without giving values in python, though =/

you can do it like this
final=[]
for i in range(6):
final.append(list(map(int,input().split())))
Now you have all your inputs in a list final

Related

How to clear an Array in Python?

I am trying to create an array and then clear it using a function, but the terminal keeps displaying 'list index out of range'.
duplicates = []
def ClearArray():
for index in range(100):
duplicates[index].append("")
ClearArray()
print(duplicates)
The instruction is to Initialise the global array Duplicates, which is a 1D array of 100 elements of data type STRING, and set all elements to empty string using a function.
You are getting the error because you are initializing an empty list and then trying to access elements inside of that list.
In the first iteration of the for loop, you attempt to access duplicates[0] but the list is empty, and therefore the list index out of range exception is raised. You can resolve this by replacing duplicates[index].append("") with duplicates.append("").
You can read more about python lists here.
In addition, according to python's PEP8 function names should be lowercase, with words separated by underscores as necessary to improve readability.
Putting it all together:
duplicates = []
def clear_array():
for index in range(100):
duplicates.append("")
clear_array()
print(duplicates)
To remove all elements of a list, you can use clear, like so:
duplicates.clear()
I am not sure what you mean by clear, but when you create a list/array in python it will not have data
In case you need to add some data
duplicates = []
print(len(duplicates)) # length should be zero
for i in range(100):
dupicates.append(i)
In case you need to clear all the data in the list
print(len(duplicates)) # Should print 100 from the above for loop
duplicates.clear()
print(len(duplicates)) # Should be 0 again considering we have cleared the data
In case you are trying to create an array of arrays
duplicates = [[]] * 100
print(duplicates) # should show you 100 lists in a list
You are trying to get something that doesn't exist.
Your list duplicates = [] has nothing in it. Therefore duplicates[0] does not exist, which is why you are getting list index out of range.
In your example:
def ClearArray():
for index in range(100):
duplicates[index].append("")
The first iteration of your for loop accesses duplicates[index] where index = 0, Which throws the error.
When you append, you add to the end. So there is no need to specify an index. So this below will work fine:
def ClearArray():
for index in range(100):
duplicates.append("")
First create a non-empty array.
Then repeat deleting the first item of this array as many times as there are items in your array.
array = [43,54,65,76]
def ClearArray(array_to_clear):
for index in range(len(array_to_clear)):
del array_to_clear[0]
ClearArray(array)
print(array)
If you don't want to delete the items of the list but you want to replace each item with an empty string, then i recommend this code :
array = [43,54,65,76]
def ClearArray(array_to_clear):
for index in range(len(array_to_clear)):
array_to_clear[index] = ""
ClearArray(array)
print(array)

Replace item in list upon negative index as input

Currently, I have a list as such:
aList = [1,2,3,4,5]
and what I'm trying to do is to emulate 'aList[index] = item' function in python. the program prompts the user for input of negative index and the item to replace.
enter negative index: -2
enter item to replace: 7
this would give me:
[1,2,3,7,5]
since, when the index is negative, python starts counting from the back of the list. Here's my code:
aList = [1,2,3,4,5]
index = int(input("Enter index:"))
item = int(input("Enter item:"))
j = -1 #-1 means the counter should begin with -1 not 0
start = len(aList)-1 #i want python to start from the back of the list
while j<start:
if j == index:
aList[j] = item
j-=1
print(lst)
I'm getting an infinite loop because of the j-=1 and I'm wondering if I'm emulating it correctly?
I think first you need to clear you concept about array.
What is Array.?
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers1, and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Array In Python
To define a list you simply write a comma separated list of items in square brackets:
myList=[1,2,3,4,5,6]
This looks like an array because you can use "slicing" notation to pick out an individual element - indexes start from 0. For example
print myList[2]
will display the third element, i.e. the value 3 in this case. Similarly to change the third element you can assign directly to it:
myList[2]=100
The slicing notation looks like array indexing but it is a lot more flexible. For example
myList[2:5]
is a sublist from the third element to the fifth i.e. from myList[2] to myList[4]. notice that the final element specified i.e. [5] is not included in the slice.
Also notice that you can leave out either of the start and end indexes and they will be assumed to have their maximum possible value. For example
myList[5:]
is the list from List[5] to the end of the list and
myList[:5]
is the list up to and not including myList[5] and
myList[:]
is the entire list.
List slicing is more or less the same as string slicing except that you can modify a slice. For example:
myList[0:2]=[0,1]
has the same effect as
myList[0]=0
myList[1]=1
Finally is it worth knowing that the list you assign to a slice doesn't have to be the same size as the slice - it simply replaces it even if it is a different size.
I am not sure why you need a loop, when you can just access the elements by index:
aList = [1,2,3,4,5]
index = int(input("Enter index:"))
item = int(input("Enter item:"))
aList[index] = item
Of course your loop is infinite...the variable 'j' keeps getting more negative and you're comparing it so 'start', which is the length of the list minus one.

generating a full combination of values from multiple lists in python?

I would like to generate a full-matrix of value combinations from multiple lists. But I don't always know how many lists will be provided, and each one can have a different length. I was able to get the answer by abusing itertools.product(), but I think it's overkill. Is there a more pythonic way?
import itertools
listoflists = [
["happy","sad"],
["car","bike","truck"],
["true","false"],
[3,6,34,8,31]]
def comboGenerator(lol):
# create a uniform N-dimensional struct, big enough to hold longest dimension
longest = max(map(lambda x: len(x),lol))
superstruct = itertools.product(range(longest), repeat=len(lol))
# visit each cell in the struct, ignore the empty ones
for a in superstruct:
combo = []
try:
for index in range(len(lol)):
combo.append(lol[index][a[index]])
yield (combo)
except IndexError: #this was an empty cell; try again
pass
for x in comboGenerator(listoflists):
print (x)
result = list(itertools.product(*listoflists))
if you want the element type of result list be a list, then convert it by:
result = [list(item) for item in result]

Struggling with a specific error.tuple indices must be integers, not float

I am struggling with a specific error
TypeError: list indices must be integers, not tuple
I have seen some previous Questions but none of these really explains what this error means. I Understand it has something to do with creating arrays/matrices.
A brief description of this error would be much appreciated.
Here is a piece of my code
def Zed(K,M):
if K == M:
return Rk(K) + Rkp + 2*1j*W*10**(-7.0)*np.log(Dkkp/Ncheck(K))
else:
return (Rk(K) + Rkp + 2*1j*W*10**(-7.0)*np.log(pythag(Conductors[K],Conductors[M],(Conductors[K+5]),((Conductors[M+5])-Dkkp))/Ncheck(K)))
for K in range(5):
for M in range(5):
ZMatrix[[K],[M]] = Zed(Conductors[K],Conductors[M]) #this is where the error apears
and it throws the error I have mentioned above. I define ZMatrix as
ZMatrix = [[0 for x in range(5)] for x in range(5)]
First of all to initialize your ZMatrix I would rather use:
ZMatrix = [[0] * 5 for i in range(5)]
Edit: I originally used * to repeat generation in two dimension, that doesn't work as indicated in python FAQ: How do I create a multidimensional list, it can only be used for one dimension, and you need to use list comprehension (or for loops) to get the second dimension.
Secondly, when dereferencing list of lists, you need to keep the reference to the different lists apart, ZMatrix[K][M], and not use a strange tuple reference, ZMatrix[[K],[M]]. So change your last line into:
ZMatrix[K][M] = Zed(Conductors[K], Conductors[M])
If this doesn't solve all of your problem, then you might need to look at the formula construction in your Zed() function.
([K][M]) is a tuple.
The correct syntax for accessing Mth column element in the Kth row is
ZMatrix[K][M]
And make sure the name 'Conductors' is defined.
This:
ZMatrix[[K],[M]]
doesn't make sense. You are passing a tuple of two lists ([K],[M]) as an index to a list ZMatrix.
Perhaps you mean:
ZMatrix[K][M]
Update:
When you have a list and want to get an element out of it, you use an index inside square brackets.
mylist[index]
The index in this case should be an integer: 0 for the first element, 1 for the second, and so on.
A tuple is (usually) multiple items separated by a comma, such as (1,2), or (True, 'banana', 4).
When you write:
ZMatrix[[K],[M]]
you are passing your list ZMatrix a tuple . The tuple is ([K],[M]).
Hence the error message "list indices must be integers, not tuple".
However, you can do this:
ZMatrix[K][M]
How this works is that ZMatrix[K] indicates element K of ZMatrix. That element itself is another list because of how ZMatrix was defined. Then we can refer to element M of the list ZMatrix[K] as ZMatrix[K][M].

initializing a 2D list in python since i dont know the exact dimensions

I want to create a python 2D list, but i will not know the ecaxt dimensions that the list has to be initialized while writing the program.
For example i want a list like this
edgelist = [[3,5], [2,5], [4,6], ...]
The inner list will have two numbers. But the number of inner list will not be known while coding. the numbers will be assigned after initializing through a loop.
My code is :
edgelist = []
val = 0
for every_list in req_data:
for temp in range(1,len(every_list)):
edgelist[val].append(every_list[0])
edgelist[val].append(every_list[temp])
val = val+1
When val == 0 the list appends the value. But the next iteration it shows the error as IndexError: list index out of range...
edgelist = []
It means that edgelist is an empty list. So, edgelist[0] will not be able to get anything. That is why it is throwing that error. What you should do is
edgelist.append([every_list[0], every_list[temp]])
This will create a two element list with every_list[0] and every_list[temp] and add that list to edgelist. So, edgelist becomes a list of lists or a 2-D list.
Also, if req_data already has two element lists, then you can simply do
for every_list in req_data:
edgelist.append(every_list[:])
This will create copies of elements in req_data and add it directly to edgelist. Its better to use list comprehension, like this
edgelist = [every_list[:] for every_list in req_data]

Categories