import re
from collections import Counter
words = re.findall('\w+', open('/Users/Jack/Desktop/testytext').read().lower())
listy = Counter(words).most_common()
theNewList = list(listy)
theNewList[1][1] = 10
#****ERROR HERE****
#Traceback (most recent call last):
# File "countTheWords.py", line 16, in <module>
# theNewList[1][1] = 10
#TypeError: 'tuple' object does not support item assignment
In my mind the list() call should convert 'listy' to a list. Any idea what I am doing wrong?
listy is a list:
>>> type(listy)
<type 'list'>
Its elements are not:
>>> type(listy[1])
<type 'tuple'>
And you're trying to modify one of their elements:
>>> type(listy[1][1])
<type 'int'>
You can convert the elements like so:
>>> listier = [list(e) for e in listy]
>>> type(listier)
<type 'list'>
>>> type(listier[1])
<type 'list'>
>>> type(listier[1][1])
<type 'int'>
And then assign:
>>> listier[1][1] = 10
>>> listier[1][1]
10
.most_common() returns a list of tuples. When you do list(listy), you're actually changing nothing. It will not change the tuples inside to lists.
As tuples are immutable, they won't let you change items in it (compared to lists which are mutable).
You can change them to lists, however, by using map():
map(list, listy)
theNewList[1] is a valid list item-access, which returns a tuple. Thus theNewList[1][1] = 10 is an attempt to assign to a tuple item. That's invalid, as tuples are immutable.
Why would you want to assign a new count anyway?
Related
a=[1,2,3]
b=[2,4,5,6]
c=set(a).intersection(b) #output is set([2])
How do i get output of just 2?
i tried list(c) but got this error:
TypeError: 'list' object is not callable
It's normal that the output is a set, after all the result of an intersection can yield more than one element. If you're interested in a list of the elements, this worked for me:
c = set(a).intersection(b)
list(c)
=> [2]
It's weird that you're getting the error 'list' object is not callable, that should not happen. Maybe you redefined list somewhere? look in your code and see if you did something like this:
list = [1, 2, 3]
...And that's exactly why it's a bad idea to redefine built-in functions.
>>> a=[1,2,3]
>>> b=[2,4,5,6]
>>> c=set(a).intersection(b)
>>> print c
set([2])
>>> print type(c)
<type 'set'>
>>> elem = c.pop()
>>> print elem
2
a=(3)
b=list(a)
typeError: 'int' object is not iterable
but
a=[3]
b=tuple(a)
c=list(b)
runs without error.
please explain this.
That's because (3) is just 3. tuples are defined by the comma, not the parentheses. If you want a tuple with one element, add a comma: (3,).
(3) is the number 3 in parentheses and (3,) is a tuple:
>>> a = (3)
>>> type(a)
<type 'int'>
>>> a = (3,)
>>> type(a)
<type 'tuple'>
There are no ambiguity with [3] so it's a list:
>>> a = [3]
>>> type(a)
<type 'list'>
The list constructor accepts a tuple or a list but not a int.
Define tuple by using comma ,
type((3,)) its of type 'tuple'
type(3) its of type 'int'
If I have a list as below:
samplist= [3,4,5,'abc']
How can I find out whether which index is a str or Int.I want to concatenate a string s='def' with the string 'abc' which is available in the list.
Assume that I am not aware I don't know anything about the string, neither the name nor its index in list. All i know is there is a string in the list samplist and I want to loop through and find it out so that it can be concatenated with string s='def'/.
for i in xrange(len(samplist)):
if isinstace(samplist[i], str):
samplist[i] += 'def'
type() command also works:
>>> list = [1, 2, 'abc']
>>> type(list)
<class 'list'>
>>> type(list[1])
<class 'int'>
>>> type(list[2])
<class 'str'>
>>> type(list[2]) is str
True
>>> type(list[1]) is str
False
Few things really confuse me, First is in lists what is the difference between
list1 = [100,200,300]
And,
list3 = [(1,1), (2,4), (3,)]
Of course, I obviously see the visual difference but I don't get what is the difference beside the parentheses.
Also what does what mean? And what does it actually do ?
When we use the operator like that
list += 1
or
list -= 1
Totally confused.
Searched a lot but seems like I am searching for wrong content.
Thanks a lot in advance.
This is a list of three numbers:
list1 = [100,200,300]
This is a list of three tuples:
list3 = [(1,1), (2,4), (3,)]
A tuple is an immutable (can't be changed without destroying and creating a new one) collection of ordered items, that are indexed by key.
This doesn't do anything except raise an error, because you cannot add a number to a list:
>>> i = [1,2,3]
>>> i += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
If you use two types that can be added together, then += adds the value on the right, to the value pointed to by the name on the left:
>>> i = 1
>>> i += 1
>>> i
2
It is the same as doing this:
>>> i = 1
>>> i = i + 1
>>> i
2
>>> list1 = [100,200,300]
>>> list3 = [(1,1), (2,4), (3,)]
>>> for item in list1:
... print("{}: {}".format(repr(item), type(item)))
...
100: <type 'int'>
200: <type 'int'>
300: <type 'int'>
>>> for item in list3:
... print("{}: {}".format(repr(item), type(item)))
...
(1, 1): <type 'tuple'>
(2, 4): <type 'tuple'>
(3,): <type 'tuple'>
list += 1
or
list -= 1
Will cause an exception - eg.
>>> list += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'type' and 'int'
unless someone has shadowed the builtin with their own variable
>>> list = 999
>>> list += 1
>>> list
1000
list1=[100,200,300] ==> is a list and element in this list is mutable means you can change the value of element by accessing any index in list, ex: list1[1]=400
list3 = [(1,1), (2,4), (3,)] ==> is a list of tubles; tuples in python represented by (). This indicates elements in tuples can't be changed. In list3, you access each tuples by using it's index; for ex list3[0] returns (1,1) which is list element. list3[0][0] returns 1 which is tuple element. The difference here is that you cannot assign like list3[0][0] = 2.
You can read more at python documentation!
def __init__(self, specfile, listfile):
self.spec=AssignmentSpec(specfile)
self.submissions={}
I don't understand the meaning of this please help, {} with nothing in it??
Its the literal way of defining a dictionary. In this case, its an empty dictionary. Its the same as self.submissions = dict()
>>> i = {}
>>> z = {'key': 42}
>>> q = dict()
>>> i == q
True
>>> d = dict()
>>> d['key'] = 42
>>> d == z
True
It means that it is an empty dictionary.
In python:
{} means empty dictionary.
[] means empty list.
() means empty tuple.
Sample:
print type({}), type([]), type(())
Output
<type 'dict'> <type 'list'> <type 'tuple'>
EDIT:
As pointed out by Paco in the comments, (1) will be considered as a number surrounded by brackets. To create a tuple with only one element in it, a comma has to be included at the end, like this, (1,)
print type({}), type([]), type((1)), type((1,))
<type 'dict'> <type 'list'> <type 'int'> <type 'tuple'>
It defines a dict type object. If you are from C#/Java background it's same to:
IDictionary<xxx> myDict = new Dictionary();
or
Map<xxx, yyy> myMap = new HashMap<xxx, yyy> ();
or in C++ (loosely, because map is mostly a tree):
map<xxx, yyy> myMap;
xxx and yyy coz python is untyped language.