python
  1. python-list-vs-tuple

Python List VS Tuple

In Python, both lists and tuples are used to store collections of data. However, there are some key differences between them.

Syntax

A list is defined using square brackets [], while a tuple is defined using parentheses ().

Example

# Example of a list
my_list = [1, 2, 3, "four", 5.0]

# Example of a tuple
my_tuple = (1, 2, 3, "four", 5.0)

Output

Both lists and tuples can be accessed using indexing or slicing.

# Accessing elements of a list
print(my_list[0])   # Output: 1
print(my_list[3])   # Output: 'four'

# Accessing elements of a tuple
print(my_tuple[0])  # Output: 1
print(my_tuple[3])  # Output: 'four'

Explanation

The main difference between lists and tuples is that a list is mutable, which means its contents can be changed after it's created. Tuples, on the other hand, are immutable, which means their contents cannot be changed once they are created.

This means that you can add, remove, or modify elements in a list, but not in a tuple. If you try to modify a tuple, you'll get a TypeError.

Use

Lists are often used when you need to store a collection of items that may change over time, or when you need to modify the contents of the collection.

Tuples, on the other hand, are often used when you need to store a collection of items that won't change over time, or when you want to define a data type with a specific number of fields.

Important Points

  • Lists are mutable, while tuples are immutable.
  • Lists are defined using square brackets [], while tuples are defined using parentheses ().
  • Lists and tuples can be accessed using indexing or slicing.

Summary

In summary, both lists and tuples are used to store collections of data in Python. Lists are mutable and defined using square brackets, while tuples are immutable and defined using parentheses. Lists are often used when you need to store a collection of items that may change over time, while tuples are often used when you need to store a collection of items that won't change over time.

Published on: