Updating tuple values in python - python

We can not update or modify tuple in python.
I am writting a code that is updating a tuple.
Why is it not giving any error?
Here is my code
tuple1=(1,'hello',5,7,8,)
tuple1=tuple1[1:3]*2
print tuple1
print tupele1[3]
Why is it showing the output without any error?
Output :('hello', 5, 'hello', 5)
5

You're not updating the tuple, you're creating a new tuple with different values.

You aren't mutating the tuple, you're rebinding the name bound to it. This is not restricted by Python.
>>> (1, 2, 3)[1] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a = (1, 2, 3)
>>> a = 4

We can not update values in a tuple,But we can reassign the variable that referer to a tuple.

* does not what you think it does. It multipyls the slice, not its contents.
tuple1[1:3] == ['hello', 5]
tuple1[1:3] * 2 == ['hello', 5, 'hello', 5]

Related

List of lists (2D array) iteration and assigning values

I have this part of code that is giving me problems, I have seen people accessing list of list elements in similar way like list[sublist][element] in examples. What exactly am I doing wrong?
fcsv = [["1", "0"]] * 6
for i in range[0, 6]:
print(fcsv[i][0])
Traceback (most recent call last):
File "F:/Python/Project/Main.py", line 54, in <module>
for i in range[0, 6]:
TypeError: 'type' object is not subscriptable
Instead of brackets [0, 6] you must use parentheses (0, 6) with range. There is also no need for 0, you can just write:
for i in range(6):

What types of heap elements can be used with heapq module in python?

In the documentation, it mentions it could be tuples. But could it be lists? If yes, then is the priority decided by the first element of the list by default? Because in the Priority Queue Implementation Notes in the documentation, they have used list to illustrate it?
Python allows you to heapify any Python iterable (lists, tuple, strings, etc).
So, yes lists and tuples can be used as elements instead of just integers but only as long as the iterable can support valid comparisons between its elements in the lexicographical order. Let's get our hands dirty.
>>> a = (0, "hello")
>>> b = (1, "word")
>>> array = [a, b]
>>> heapq.heapify(array)
>>> heapq.heappop(array)
(0, 'hello')
All looks good, we were able to heapify a list of tuples where each tuple contains an int and a string. Let's look at another example:
>>> a = (0, "hello")
>>> b = ("word", 1)
>>> array = [a, b]
>>> heapq.heapify(array)
>>> heapq.heapify(array)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
As you can see, python interpreter starts complaining because it could not compare int & str.
For the same reasons, you won't be able to heapify a list of dictionary (List[Dict]) but you would be able to heapfiy a list of int (List[int]) or even a list of list of int (List[List[int]]). Here is the proof:
>>> a = {0:'hello', 1:'world'}
>>> b = {0:'hola', 1:'mundo'}
>>> array = [a, b]
>>> heapq.heapify(array)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'
>>>
>>>
>>> a = [1,2,3,4]
>>> b = [5,6,7]
>>> array = [a, b]
>>> heapq.heapify(array)
>>> heapq.heappop(array)
[1, 2, 3, 4]

python without comma after variables lead to TypeError: 'int' object is not iterable [duplicate]

This question already has an answer here:
Unintentional trailing comma that creates a tuple
(1 answer)
Closed 4 years ago.
people = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
p = people[0]
a = []
a+=p[0]
TypeError Traceback (most recent call last)
<ipython-input-57-244e88383d16> in <module>()
2 a = []
3 type(p[0])
----> 4 a+=p[0]
5 print(a)
TypeError: 'int' object is not iterable
When I add comma after a+=p[0] to change it into a+=p[0],. It works. Why? What does this comma do in this line of code?
The comma creates a tuple.
1 # int
1, # a tuple, equivalent of (1,)
Since you can only add an iterable to a list, you can add a tuple but can't add an integer.
Because p[0] is equal to 7 and hence can't be concatenated with another list. I don't know what you want to accomplish here, the only change I could suggest is
a += [p[0]] # or a.append(p[0]) if you don't mind mutating the original object
As far as adding a comma to the same is concerned, it works because implicitly it creates a tuple as #ForceBru suggested.
a is a list and the += operator expects an iterable to append to the list:
>>> a = []
>>> a += [1, 2, 3]
>>> a += 1, 2, 3
>>> a += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
The reason why this works is that adding a , to a number makes a tuple out of it, see:
>>> b = 1,
>>> type(b)
<class 'tuple'>

What's the difference between lists enclosed by square brackets and parentheses in Python?

>>> x=[1,2]
>>> x[1]
2
>>> x=(1,2)
>>> x[1]
2
Are they both valid? Is one preferred for some reason?
Square brackets are lists while parentheses are tuples.
A list is mutable, meaning you can change its contents:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
while tuples are not:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Note that, as many people have pointed out, you can add tuples together. For example:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
Whereas, if you were to construct this same example with a list, y would also be updated:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
One interesting difference :
lst=[1]
print lst // prints [1]
print type(lst) // prints <type 'list'>
notATuple=(1)
print notATuple // prints 1
print type(notATuple) // prints <type 'int'>
^^ instead of tuple(expected)
A comma must be included in a tuple even if it contains only a single value. e.g. (1,) instead of (1).
They are not lists, they are a list and a tuple. You can read about tuples in the Python tutorial. While you can mutate lists, this is not possible with tuples.
In [1]: x = (1, 2)
In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython console> in <module>()
TypeError: 'tuple' object does not support item assignment
Another way brackets and parentheses differ is that square brackets can describe a list comprehension, e.g. [x for x in y]
Whereas the corresponding parenthetic syntax specifies a tuple generator: (x for x in y)
You can get a tuple comprehension using: tuple(x for x in y)
See: Why is there no tuple comprehension in Python?
The first is a list, the second is a tuple. Lists are mutable, tuples are not.
Take a look at the Data Structures section of the tutorial, and the Sequence Types section of the documentation.
Comma-separated items enclosed by ( and ) are tuples, those enclosed by [ and ] are lists.
( thanx Robert for clarification, below is only in case of using listcomprehensions : )
! another very important difference is that with round brackets we will have a generator and so the memory consumption is much lower in comparison to list with square brackets
esspecially when you deal with big lists - generator will eat not only significantly less memory but also will take much less time 'cause you will not need to prebuilt objects in list

python reduce error?

The following is my python code:
>>> item = 1
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> sums=reduce(lambda x:abs(item-x[1]),a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>>
How can I fix it?
Thanks!
Your lambda takes only one argument, but reduce requires a function that takes two arguments. Make your lambda take two arguments.
Since you didn't say what you want this code to do, I'll just guess:
the_sum=reduce(lambda x,y:abs(y[1]-x[1]),a)
Your problem itself is a bit unclear. Anyway, i have taken just assumption--
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> a
[(1, 2, 3), (7, 2, 4)] # list of tuples
I am assuming that you might be interested in getting the sum of all the elements in the list. If that is the problem then that could be solved in 2 steps
1) The first step should be to flatten the list.
2) And then add all the elements of the list.
>>> new_list = [y for x in a for y in x] # List comprehension used to flatten the list
[1, 2, 3, 7, 2, 4]
>>> sum(new_list)
19
One liner
>>> sum([y for x in a for y in x])
19
Another assumption, if your problem is to minus every element of tuple by item in the list then use this:
>>> [tuple(map(lambda y: abs(item - y), x)) for x in a]
[(0, 1, 2), (6, 1, 3)] # map function always returns a list so i have used tuple function to convert it into tuple.
If the problem is something else then please elaborate.
PS: Python List comprehension is far better and efficient than anything else.
reduce expects the function it is given to accept 2 arguments. For every item in the iterable it will pass the function the current item, and the previous return value from the function. So, getting the sum of a list is reduce(lambda: x,y: x+y, l, 0)
If I understand correctly, to get the behavior you were trying to get, change the code to:
a_sum = reduce(lambda x,y: x + abs(item-y[1]), a, 0)
But I might be mistaken as to what you were trying to get.
Further information is in the reduce function's docstring.

Categories

Resources