Python: difference between list and tuple with examples



Lists and tuples both are used to store data in a sequence in Python. Lists are enclosed in square brackets [ ], whereas tuples are enclosed in parentheses ( ).

Here is an example of creating a list in Python:

cv_list = [1, 2, 3, 4, 5]


And here is an example of creating a tuple in Python:


cv_tuple = (1, 2, 3, 4, 5)


To access elements in a list or tuple, you use indexing and slicing. The first element in a list or tuple has an index of 0.

Here is an example of indexing in a list:


print(cv_list[0]) # Output: 1


And here is an example of indexing in a tuple:


print(cv_tuple[0]) # Output: 1


You can also slice a list or tuple to access a range of elements. To slice a list or tuple, you specify the start index and end index separated by a colon :.

Here is an example of slicing a list:


print(cv_list[1:3]) # Output: [2, 3]


And here is an example of slicing a tuple:

print(cv_tuple[1:3]) # Output: (2, 3)


In summary, lists and tuples are both useful data structures in Python, but they have some fundamental differences. Lists are mutable, while tuples are immutable. Lists are used when you need to add, remove, or change elements, while tuples are used when you need to store a collection of elements that won't change. Understanding the differences between these two data structures will help you make the right choice for your program.

No comments:

Post a Comment