Accessing multi-dimensional list in Python - python

I have a list as follows in my python script:
a = [["iguana","i"],["mycat","m"]]
I want to access individual elements of the list and print them:
print a[0,0]
print a[1,1]
But this throws "TypeError: list indices must be integers, not tuple".
How can I access individual elements of the list?
Thanks

Index them one at a time:
>>> a = [["iguana","i"],["mycat","m"]]
>>> a[0]
['iguana', 'i']
>>> a[0][0]
'iguana'
>>> a[1][0]
'mycat'
>>>
The first [n] indexes list a, which returns a list, and the second indexes that list.

Related

Itirating through list of tuples with nested for loops

I have a list containing tuples. Each tuple holds 2 elements. I tried to print it with the following code, but it gives the error message:
TypeError: list indices must be integers or slices, not tuple
Relevant code:
for i in list:
for j in [1, 2]:
print(list[i][j])
With the idea of printing each element of the 1st tuple, each element of the 2nd tuple etc
Realise i in the loop is actually a tuple (an element of a list). So, you just need to print element of i like i[j]. list[i] makes no sense as i should be an integer, but it is actually an element of the list, that is a tuple. You must also be getting an error like this TypeError: list indices must be integers, not tuple. Well I am. So that should be a hint/explanation to you.
lst = [(1,2),(5,9)]
for i in lst:
for j in [0, 1]:
print(i[j])
print
Output:
1 2
5 9
You can unpack the tuple in the for loop
>>> tup_list = [(1,2), (3,4)]
>>> for a,b in tup_list:
... print(a,b)
...
1 2
3 4
You can use nested list comprehension:
[i for subset in list for i in subset] give you flat list
It's more pythonic!

python if statement to check a column for a value and do a command

for z in range(0,countD.shape[0]):
if countD[z,0] in background_low1[:,0]:
background_lowCountD.append(countD[z,:])
else:
background_goodCountD.append(countD[z,:])
I'm using the above code and getting a "list indices must be integers, not tuple" error message. I have two uneven arrays (CountD and background_low1), If a value is present in column 0 of both arrays at any row level I want to move that row to a new array, if its only present in 1 I want that row moved to a second new array.
You are getting this error message because lists are unidimensional (in theory). But since a list can contain another list, you can create a multidimensional list. Now accessing an element of a list is done using an index (which must be an integer) between brackets. When dealing with multidimensional lists, just use multiple brackets one after the other :
>>> a = ['a','b','c']
>>> b = [1,2,a]
>>> print b[2]
>>> ['a','b','c']
>>> print b[2][0]
>>> 'a'
So, to answer your question, try something like this :
list1 = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
list2 = [[1,4,5,6],
[7,6,7,8],
[9,1,2,3]]
newList = []
otherList = []
#you need to make sure both lists are the same size
if len(list1) == len(list2):
for i in range(len(list1)):
if list1[i][0] == list2[i][0]:
newList.append(list1[i])
else:
otherList.append(list1[i])
#the lists should now look like this
>>> print newList
>>> [[1,2,3,4],[9,10,11,12]]
>>> print otherList
>>> [[5,6,7,8]]

Variable functions as a list but isn't technically a list? [Python]

I'm pulling a list from a dictionary like so:
d={foo:[1,2,3]}
thelist=d[foo]
I'm able to get items from indexes of thelist but not like this:
for i in thelist:
print thelist[i]
I get an error saying the "list index is out of range"
Additionally, when I run
thelist is list
it returns False
whats going on here
the list index out of range is because thelist[3] is not an allowed thing to call.
the for loop is trying to print thelist[i] for each i in thelist. In this case thelist has 1, 2, and 3. So it's trying to print thelist[1] (which is 2), thelist[2] (which is 3), and then thelist[3] which is undefined.
A bit more detail:
thelist = ['puppy', 1, 'dog']
for i in thelist:
print i
gives
puppy
1
dog
as for thelist is list, instead try type(thelist). The type of thelist is list. So testing whether thelist is list (that is it is the class of things which we call list) rather than is a list (that is it is an example of the list class) will return False.
If you want to interate over a list using indices, than you should do as follows:
for i,v in enumerate(thelist):
print(thelist[i])
Or alternatively:
for i in range(len(thelist)):
print(thelist[i])
in python the default indexing strart from 0 and ends to its lenght-1
so thelist=d[foo] ie [1,2,3] will have index 0,1,2
for i in thelist: # here i the element of list not index
print thelist[i]
for i in range(len(thelist)): # here i the index of list
print thelist[i]
for l1 in thelist:
print l1
you get:
1
2
3
in your code you're trying to access list using the list elements as index. Instead, to iterate over list' indexes, you should use range(len(theList))(from 0 to len(theList) -1) or reversed(range(len(theList)) (from len(theList) -1 to 0).
to check if a variable is a list use types
import types
x = [1,2,3]
if type(x) is types.ListType:
print 'x is a list'
Each time you go through the for loop, i is set to one of the items in the list.
You'll also want to use the type() function to compare the types of thelist and a list (really []).
d={'foo':[1,2,3]}
thelist = d['foo']
for i in thelist:
print i
print type(thelist)
print type(thelist) is type([])
returns
1
2
3
<type 'list'>
True

Printing specific items out of a list

I'm wondering how to print specific items from a list e.g. given:
li = [1,2,3,4]
I want to print just the 3rd and 4th within a loop and I have been trying to use some kind of for-loop like the following:
for i in range (li(3,4)):
print (li[i])
However I'm Getting all kinds of error such as:
TypeError: list indices must be integers, not tuple.
TypeError: list object is not callable
I've been trying to change () for [] and been shuffling the words around to see if it would work but it hasn't so far.
Using slice notation you can get the sublist of items you want:
>>> li = [1,2,3,4]
>>> li[2:]
[3, 4]
Then just iterate over the sublist:
>>> for item in li[2:]:
... print item
...
3
4
You should do:
for i in [2, 3]:
print(li[i])
By range(n), you are getting [0, 1, 2, ..., n-1]
By range(m, n), you are getting [m, m+1, ..., n-1]
That is why you use range, getting a list of indices.
It is more recommended to use slicing like other fellows showed.
li(3,4) will try to call whatever li is with the arguments 3 and 4. As a list is not callable, this will fail. If you want to iterate over a certain list of indexes, you can just specify it like that:
for i in [2, 3]:
print(li[i])
Note that indexes start at zero, so if you want to get the 3 and 4 you will need to access list indexes 2 and 3.
You can also slice the list and iterate over the lists instead. By doing li[2:4] you get a list containing the third and fourth element (i.e. indexes i with 2 <= i < 4). And then you can use the for loop to iterate over those elements:
for x in li[2:4]:
print(x)
Note that iterating over a list will give you the elements directly but not the indexes.

Add two lists in Python

I am trying to add together two lists so the first item of one list is added to the first item of the other list, second to second and so on to form a new list.
Currently I have:
def zipper(a,b):
list = [a[i] + b[i] for i in range(len(a))]
print 'The combined list of a and b is'
print list
a = input("\n\nInsert a list:")
b = input("\n\nInsert another list of equal length:")
zipper(a,b)
Upon entering two lists where one is a list of integers and one a list of strings I get the Type Error 'Can not cocanenate 'str' and 'int' objects.
I have tried converting both lists to strings using:
list = [str(a[i]) + str(b[i]) for i in range(len(a))]
however upon entering:
a = ['a','b','c','d']
b = [1,2,3,4]
I got the output as:
['a1','b2','c3','d4']
instead of what I wanted which was:
['a+1','b+2','c+3','d+4']
Does anyone have any suggestions as to what I am doing wrong?
N.B. I have to write a function that will essentially perform the same as zip(a,b) but I'm not allowed to use zip() anywhere in the function.
Zip first, then add (only not).
['%s+%s' % x for x in zip(a, b)]
What you should do
You should use
list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]
instead of
list = [str(a[i]) + str(b[i]) for i in range(len(a))]
In your version, you never say that you want the plus character in the output between the two elements. This is your error.
Sample output:
>>> a = [1,2,3]
>>> b = ['a','b','c']
>>> list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]
>>> list
['1+a', '2+b', '3+c']

Categories