Python tuples work like lists for indexing, slicing and membership checks, but they cannot be changed.
You must add a comma after the value, like 1 comma inside the brackets. Without it, Python cannot tell whether you are writing one value in brackets or a new tuple, so it creates a class int instead. The instructor calls this the biggest confusion of Python developers.
A tuple is very similar to a list, but you cannot change it. With a list, assigning a new value to index 0 works, but with a tuple Python raises a TypeError saying the tuple object does not support item assignment. Tuples are immutable, while lists are mutable.
Sometimes you intentionally want things not to change. For example, when working on a very complex program, you might want a kind of constant list that nobody changes by mistake. In that case the instructor recommends using a tuple, since its values cannot be modified.
Printing an index such as 34 on a short tuple causes an error saying the tuple index is out of range. The program still runs up to that line, so the earlier prints show 1, 2 and 76, the values at the 0th, 1st and 2nd index.
It works exactly as with lists. To resolve an index like minus 1, take the tuple's length and subtract. In the demo, printing len gives a length of 7, so minus 1 becomes index 6, counting 0, 1, 2, 3, 4, 5, 6 to find the element.
Use the in keyword with an if condition, for example checking if 342 is in the tuple. Since 342 is present, the message prints. If you check a value like 3421 that is not present, the condition evaluates to false and nothing is printed.
No. Tuples can be sliced like lists, but slicing returns a new tuple and leaves the original unchanged. In the demo, slicing from 1 to 4 creates a new tuple containing 2, 76 and 342, following the same rules as list slicing, including blank start and end values.
If the start is blank, Python automatically puts 0 there. If the end is blank, it uses the length of the tuple. The instructor notes this is exactly the same as he explained for lists, and negative indices can be converted into positive ones first.
“This is the biggest confusion of Python developers.”
“sometimes you'll want things to not change intentionally.”
“After slicing, a new tuple is returned. So, the tuple doesn't change.”
“Tuples are immutable.”
“Tuples in Python | Python Tutorial - Day #24.” https://www.youtube.com/watch?v=PipsOUDKrVk. Transcript summary by WhipScribe, https://whipscribe.com/transcript-pages/tuples-in-python-python-tutorial-day-24.html.