Itirating through list of tuples with nested for loops - python

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!

Related

Error: list indices must be integers or slices, not tuple

Trying to read an input that coincides with abjadMapV. Then return the char in AbjadMap. But i keep getting this error.
def show(ln):
abjadMapV=[1,2,3,4,5,6,7,8,9,
10,20,30,40,50,60,70,80,90,
100,200,300,400,500,600,700,800,900,
1000,29]
abjadMap=['\u0627','\u0628','\u062C','\u062F','\u0647','\u0648','\u0632','\u062D','\u0637',
'\u064A','\u0643','\u0644','\u0645','\u0646','\u0633','\u0639','\u0641','\u0635',
'\u0642','\u0631','\u0634','\u062A','\u062B','\u062E','\u0630','\u0636','\u0638',
'\u063A','\uFEFC']
abjadN=["alif","ba","jeem","dal","haa","waw","za","ha","da",
"ya","kahf","laam","meem","noon","seen","ayn","fa","sadh",
"qaf","ra","sheen","ta","tha","kha","thal","dhad","za",
"gayn","lam alif"]
i=0
for i in enumerate(abjadMapV):
if ln in abjadMapV[i] :
print(i)
print(abjadMap[i])
return abjadMap[i]
b=input()
a=show(b)
print(a)
Edited to new code trying to get show to return the index
def show(ln):
abjadMapV=[1,2,3,4,5,6,7,8,9,
10,20,30,40,50,60,70,80,90,
100,200,300,400,500,600,700,800,900,
1000,29]
abjadMap=['\u0627','\u0628','\u062C','\u062F','\u0647','\u0648','\u0632','\u062D','\u0637',
'\u064A','\u0643','\u0644','\u0645','\u0646','\u0633','\u0639','\u0641','\u0635',
'\u0642','\u0631','\u0634','\u062A','\u062B','\u062E','\u0630','\u0636','\u0638',
'\u063A','\uFEFC']
abjadN=["alif","ba","jeem","dal","haa","waw","za","ha","da",
"ya","kahf","laam","meem","noon","seen","ayn","fa","sadh",
"qaf","ra","sheen","ta","tha","kha","thal","dhad","za",
"gayn","lam alif"]
i=0
for i in abjadMapV:
if ln == i:
return abjadMap.index(i)
b=input()
a=show(b)
print(a)
The function enumerate returns tuple. So in line
print(abjadMap[i]) # i here is tuple.
And you have figured out that the list indices must be integer not Tuple.
Therefore edit your code accordingly.
If you are not familiar with enumerate function look at the example given below:
l=['a','b','c']
k=enumerate(l)
enumerate function returns iterable object:
so k is an iterable object,
next(k)
gives the output:
(0,'a')
that means 0 is the index of a in list l.
for i in enumerate(l)
i is an tuple not an integer.
enumerate() returns a list of tuples, each being an index-value pair. You may destructure while iterating through them to solve the issue:
for i,j in enumerate(abjadMapV):
if ln in j: # j is the value i. e. j = abjadMap[i]
print(i) # i is the index
print(abjadMap[i] )
return abjadMap[i]
You may otherwise iterate through range(len(abjadMapV)) and use the variable as the index.

Printing tuple indexed [:1] works, but [0] produces TypeError

fhand = open(raw_input('Enter a file name: '))
counts = dict()
words = []
for lines in fhand:
if lines.startswith('From') and not lines.startswith('From:'):
words = lines.split()
if words[1] not in counts:
counts[words[1]] = 1
else:
counts[words[1]] += 1
lst = list()
for key, val in counts.items():
lst.append((val, key))
lst.sort(reverse=True)
for key, val in lst[0]:
print key, val
The part in question is:
for key, val in lst[0]:
print key, val
This gives me: TypeError: 'int' object is not iterable. I have figured out that for some reason this does work:
input:
for key, val in lst[:1]:
print key, val
output:
Enter a file name: mbox-short.txt
5 cwen#iupui.edu
I'm just trying to figure out why exactly this works but not [0]. And as always, thank you for the help!
You have to realize the difference between [0] and [:1]
What [0] does is return to you the value that is stored at index 0 of the list.
On the other hand, when you do [:1], you are slicing the list, meaning you're getting all the elements of the list with index from 0 (inclusive) up to 1 (non inclusive).
From the documentation:
All slice operations return a new list containing the requested elements.
So when you slice a list, you're also getting back a list. And lists, being iterable types, can be -well- iterated! And this is true even if they contain only one element.
When you do for key, val in lst[0], you're trying to iterate a single value, the one that is stored at index 0 in lst. However, when instead of [0] you do [:1], what is returned isn't a single value but a range of values. In your case it may contain only one value, but it is still a range and therefore can be iterated in a for loop.
For a simpler explanation, see this great answer by Greg Hewgill on how list slices work.
Consider something like:
lst = [1, 2, 3]
lst[0] is an int (1) and an int is not iterable. However, lst[:1] is another list and therefore it is iterable.
In your case, you have a list of 2-tuples. so lst[0] is a 2-tuple -- Which is iterable. However, iterating over the 2-tuple will give you individual items which are not iterable and therefore cannot be unpacked into key, val. On the flip side, lst[:1] gives you a new list that holds 2-tuples. The list can be iterated and then the 2-tuples can be unpacked into key/value pairs.
list[0] returns an object, the element at index 0, but the for in loop syntax expects something iterable like a list of objects.
list[:1] slices the list into a new list that just includes the first element and so it will work.

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.

Accessing multi-dimensional list in 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.

Categories