Lists and Tuples

Lists and tuples are two fundamental data structures in Python used to store collections of items. This tutorial provides an overview of lists and tuples, including their creation, manipulation, and differences.

Lists

A list is an ordered collection of items that can be of different data types. Lists are mutable, meaning you can change their contents after creation.

Creating a List

You can create a list in Python by enclosing items within square brackets [].


      # Creating a list of integers
      numbers = [1, 2, 3, 4, 5]

      # Creating a list of strings
      fruits = ["apple", "banana", "orange"]
      

Accessing Elements

You can access individual elements in a list using their index. Indexing starts from 0 for the first element.


      # Accessing the first element
      first_element = numbers[0]  # Output: 1

      # Accessing the third element
      third_element = fruits[2]  # Output: "orange"
      

Modifying Elements

Lists are mutable, so you can modify their elements after creation.


      # Modifying the second element
      numbers[1] = 10
      console.log(numbers);  // Output: [1, 10, 3, 4, 5]
      

List Methods

Python provides various methods to manipulate lists:


      # Adding an element to the end of the list
      fruits.append("grape")

      # Inserting an element at a specific index
      fruits.insert(1, "kiwi")

      # Removing an element by its value
      fruits.remove("banana")

      # Sorting the list
      numbers.sort()

      # Reversing the list
      fruits.reverse()
      

Tuples

A tuple is an ordered collection of items similar to lists, but with one key difference: tuples are immutable, meaning their elements cannot be changed after creation.

Creating a Tuple

You can create a tuple in Python by enclosing items within parentheses ().


      # Creating a tuple of integers
      coordinates = (10, 20)

      # Creating a tuple of strings
      colors = ("red", "green", "blue")
      

Accessing Elements

Similar to lists, you can access individual elements in a tuple using their index.


      # Accessing the first element
      first_coordinate = coordinates[0]  # Output: 10

      # Accessing the second element
      second_color = colors[1]  # Output: "green"
      

Tuple Methods

Since tuples are immutable, they have fewer methods compared to lists. Some common operations include:


      # Concatenating tuples
      new_tuple = coordinates + (30, 40)

      # Counting occurrences of an element
      count_red = colors.count("red")
      

Summary

List Tuple
Mutable Immutable
Ordered Ordered
Indexing/slicing supported Indexing/slicing supported
Duplicate elements allowed Duplicate elements allowed