1 min read

Python Lists and Tuples: A Quick Overview

Lists and tuples are fundamental data structures in Python, used to store collections of items. They differ primarily in their mutability, which refers to their ability to be changed after creation.  

Lists

  • Mutable: Lists are mutable, meaning you can add, remove, or modify elements after they're created.  
  • Syntax: Enclosed in square brackets [].

Example:Python

my_list = [1, 2, 3, "apple", "banana"]

Tuples

  • Immutable: Tuples are immutable, meaning their contents cannot be changed once they're created.  
  • Syntax: Enclosed in parentheses ().

Example:Python

my_tuple = (10, 20, "hello")

Key Differences:

FeatureListsTuples
MutabilityMutableImmutable
Syntax[]()
Use CasesDynamic data that needs frequent changesFixed data that doesn't need modification

Export to Sheets

Common Operations:

Both lists and tuples support various operations, including:

  • Indexing: Accessing elements by their position.
  • Slicing: Extracting a portion of the sequence.  
  • Concatenation: Combining two sequences.  
  • Length: Determining the number of elements.  

Example:

Python

my_list = [1, 2, 3]
my_tuple = (4, 5, 6)

# Accessing elements
print(my_list[0])  # Output: 1
print(my_tuple[1])  # Output: 5

# Slicing
print(my_list[1:3])  # Output: [2, 3]
print(my_tuple[:2])  # Output: (4, 5)

# Concatenation
combined_list = my_list + [7, 8]
print(combined_list)  # Output: [1, 2, 3, 7, 8]

# Length
print(len(my_tuple))  # Output: 3

By understanding the distinction between lists and tuples, you can effectively choose the appropriate data structure for your specific needs in Python programming.