python lists vs tuples

as with any programming language, python has a bunch of data types necessary to exitst or be considered as a programming language.

from strings to floats, integers to dictionaries, booleans to sets, these basic data types are all necessary for basic-to more complex expressions and programs.

Of these data types, we'll be considering 2 similar, but not so similar data types than could confuse beginners, lists and tuples.

python is one of a few languages that has this data-type "tuples" and we'll see the difference between tuples and lists in this shorticle.

there are 2 main differences between a list and a tuple:

##lists are immutable lists are denoted by brackets and are immutable. basically, this means elements within a list can be reassigned, or changed.

if you have a list:

list1=[0,1,2,3,4,5,6,7]

you can reassign an element like so:

list1[1]=3
list1

this reassigns the second element to the value 3, giving you: [7, 5, 4, 3, 2, 1, 0]

this shows the basic characteristic of mutability you can perform a variety of other functions on lists such as slicing, deleting or reassigning it whole or its individual elements.

tuples are immutable

as you may be guessing, this is the opposite of mutable. tuples, denoted by parenthesis, cannot be reassigned once created. their individual values remain the same and cannot be reassigned. as we can see:

tuple1=(0,1,2,3,4,5,6,7)
tuple[1]=3
tuple1

you get an error:

TypeError: ‘tuple’ object does not support item assignment

As you can see, a tuple doesn’t support item assignment.

however, the entire tuple can be reassigned:

mytuple=2,3,4,5,6
mytuple

(2,3,4,5,6)

you can slice a tuple, reassign it whole, or delete it whole, But you cannot delete or reassign just a few elements or a slice.

these are the main differences between lists and tuple in python, keeping these in mind are useful in various problem solving cases where you may or may not want a variable to be reassigned.