Wednesday, January 1, 2025

Python Lists

 In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe stored at different locations.

  • List can contain duplicate items.
  • List in Python are Mutable. Hence, we can modify, replace or delete the items.
  • List are ordered. It maintain the order of elements based on how they are added.
  • Accessing items in List can be done directly using their position (index), starting from 0.

nested lists in python : matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Access element at row 2, column 3
print(matrix[1][2])

Another program to find pair of numbers in a sorted array that sum to a value(target):

def pair_sum_sorted_all_pairs(arr, target):

  """

  Finds all pairs in a sorted array that sum to a given target.

  Args:

    arr: A sorted array of integers.

    target: The target sum.

  Returns:

    A list of tuples representing the pairs.

  """

  result = []

  left, right = 0, len(arr) - 1

  while left < right:

    current_sum = arr[left] + arr[right]

    if current_sum == target:

      result.append((arr[left], arr[right]))

      left += 1

      right -= 1

    elif current_sum < target:

      left += 1

    else:

      right -= 1


  return result


if __name__=="__main__":

    arr = [1, 2, 3, 4, 5, 6, 7]

    target = 8

    print(pair_sum_sorted_all_pairs(arr, target))

When we run this program here we get following output:


C:\Users\kamat>python untitled123.py

[(1, 7), (2, 6), (3, 5)]

No comments:

Post a Comment