• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Python | Lists
  1. Notes
  2. Creating & Accessing Lists
  3. Adding & Modifying Items
  4. Removing Items
  5. Sorting & Reversing
  6. Searching & Indexing
  7. Looping & Iteration
  8. List Comprehensions
  9. Slicing & Copying
  10. Other Lists functions

  1. Notes
    A list is a mutable collection of ordered items.
    Items in the list can be of any type, including mixed types within the same list: strings, numbers, dictionaries, lists, objects, ...
    List allow duplicates and elements can be added or removed dynamically.
  2. Creating & Accessing Lists
    • Creating basic lists
      Use square brackets ([]) to create a list.
      Use commas to separate items in the list.
      # empty list
      print([]) # Output: []
      print(list()) # Output: []
      
      # default values
      print(['a', 'b', 'c']) # Output: ['a', 'b', 'c']
      print(["a", "b", "c"]) # Output: ['a', 'b', 'c']
      
      # mixed types
      print([['a', 'b'], ['c', 'd'], 1]) # Output: [['a', 'b'], ['c', 'd'], 1]
      
      # type/isinstance methods
      print(type([])) # Output: <class 'list'>
      print(isinstance([], list)) # Output: True

    • Accessing items in a list
      To access an item in a list, you use square brackets ([]) with the index of that item in the list.
      The index of the first item in the list is 0, and the next one is 1, ...
      You can access items in a list from the last index using negative numbers.
      The index of the last item is -1, and the one before the last one is -2, ...
      x = ['a', 'b', 'c']
      print(x[0]) # Output: a
      print(x[1]) # Output: b
      print(x[-1]) # Output: c
      print(x[-2]) # Output: b
      If the list is empty, using any index to access an item in the list will return an error.
      Using an index that's higher than the list size will return an error.
      y = []
      # Raise IndexError: list index out of range
      #y[0]
      #y[1]
      #y[-1
      
      z = ["a"]
      # Raise IndexError: list index out of range
      #z[1]
      #z[-2]
  3. Adding & Modifying Items
    • Appending items to the end of a list
      x = ['a', 'b', 'c']
      x.append('d')
      print(x) # Output: ['a', 'b', 'c', 'd']

    • Inserting items into a list at specific position
      x.insert(0, 'x')
      print(x) # Output: ['x', 'a', 'b', 'c', 'd']

    • Adding items from list
      x.extend(['y', 'z'])
      print(x) # Output: ['x', 'a', 'b', 'c', 'd', 'y', 'z']

    • Adding lists (new list created)
      print(['a', 'b'] + ['c', 'd']) # Output: ['a', 'b', 'c', 'd']

    • Modifying items in a list
      x = ['a', 'b', 'c', 'd']
      # you can modify an item from any position in the list
      x[0] = 'A'
      print(x) # Output: ['A', 'b', 'c', 'd']

    • Modifying multiple items with slicing
      x = ['a', 'b', 'c', 'd']
      x[1:3] = ['B', 'C']
      print(x) # Output: ['a', 'B', 'C', 'd']

    • Inserting multiple items with slicing
      x = ['a', 'b', 'c', 'd']
      x[2:2] = ['X', 'Y']
      print(x) # Output: ['a', 'b', 'X', 'Y', 'c', 'd']
  4. Removing Items
    • Removing an item using the del method
      x = ['a', 'b', 'c', 'd']
      # you can remove an item from any position in the list
      del x[0]
      print(x) # Output: ['b', 'c', 'd']

    • Removing item using the del method and slicing
      x = ['a', 'b', 'c', 'd']
      # you can remove an item from any position in the list
      del x[1:3]
      print(x) # Output: ['a', 'd']

    • Removing the last item in a list
      x = ['a', 'b', 'c', 'd']
      # the item removed can be assigned or printed if needed
      last = x.pop()
      print(last) # Output: d
      print(x) # Output: ['a', 'b', 'c']

    • Removing an item from a specific position in a list
      x = ['a', 'b', 'c', 'd']
      # the item removed can be assigned or printed if needed
      second = x.pop(1)
      print(second) # Output: b
      print(x) # Output: ['a', 'c', 'd']

    • Removing an item by its value from a list
      x = ['a', 'b', 'c', 'c']
      # the function remove deletes only the first occurrence of the value
      x.remove('c')
      print(x) # Output: ['a', 'b', 'c']

    • Removing all items
      x = ['a', 'b', 'c', 'd']
      x.clear()
      print(x) # Output: []
  5. Sorting & Reversing
    • Sorting permanently a list: sort()
      x = ['b', 'd', 'a', 'c']
      
      x.sort()
      print(x) # Output: ['a', 'b', 'c', 'd']
      
      x.sort(reverse=True)
      print(x) # Output: ['d', 'c', 'b', 'a']

    • Sorting temporarily a list: sorted()
      x = ['b', 'd', 'a', 'c']
      print(sorted(x)) # Output: ['a', 'b', 'c', 'd']
      print(sorted(x, reverse=True)) # Output: ['d', 'c', 'b', 'a']
      print(x) # Output: ['b', 'd', 'a', 'c']

    • Sorting with key function
      # sort by length
      x = ['a', 'ab', 'abc', 'abcd']
      x.sort(key=len, reverse=True)
      print(x) # Output: ['abcd', 'abc', 'ab', 'a']
      
      # case-insensitive sorting
      x = ['Abcd', 'abC', 'aB', 'A']
      x.sort(key=str.lower)
      print(x) # Output: ['A', 'aB', 'abC', 'Abcd']
      
      # using lambda
      x = ['a', 'ab', 'abc', 'abcd']
      x.sort(key=lambda i: len(i), reverse=True)
      print(x) # Output: ['abcd', 'abc', 'ab', 'a']

    • Reversing items of a list (no sorting)
      x = ['b', 'd', 'a', 'c']
      x.reverse()
      print(x) # Output: ['c', 'a', 'd', 'b']
      x.reverse()
      print(x) # Output: ['b', 'd', 'a', 'c']

    • Reversing items of a list using slicing (no sorting)
      x = ['b', 'd', 'a', 'c']
      y = x[::-1] # new list created
      print(y) # Output: ['c', 'a', 'd', 'b']
      print(x) # Output: ['b', 'd', 'a', 'c']
  6. Searching & Indexing
    • Finding first occurrence of an element
      # index(ITEM) - returns first index of item
      x = ['a', 'a', 'b']
      print(x.index('a')) # Output: 0
      
      # index(ITEM, START_INDEX) - returns first index of item starting from START_INDEX
      print(x.index('a', 1)) # Output: 1
      
      # index(ITEM, START_INDEX, END_INDEX) - returns first index of item between START_INDEX and END_INDEX
      print(x.index('a', 1, 2)) # Output: 1

    • Membership
      print('A' in ['A', 'B']) # Output: True
      print('A' not in ['A', 'B']) # Output: False
  7. Looping & Iteration
    • Looping through a list
      x = ['b', 'd', 'a', 'c']
      for y in x:
        print(y)
      Output:
      b
      d
      a
      c

    • Using the range() function
      The range function has two parameters.
      The value of the first parameter is inclusive in the range.
      The value of the second parameter is exclusive from the range.

      for x in range(1, 3): # in language C, this is similar to: for (int i=1, i < 3, i++) ...
        print(x)
      Output:
      1
      2

    • Making a list of numbers using range() function
      x = list(range(0, 4))
      print(x) # Output: [0, 1, 2, 3]
      
      x = list(range(1, 4))
      print(x) # Output: [1, 2, 3]

    • The enumerate() function
      The enumerate() function returns a key-value pair for each item in a list.
      the key is the index of the item in the list and the value is the item.
      x = ["a", "b", "c"]
      for index, item in enumerate(x):
        print(f"{index}:{item}")
      Output:
      0:a
      1:b
      2:c

    • Starting enumerate from a specific number
      x = ["a", "b", "c"]
      for index, item in enumerate(x, start=1):
        print(f"{index}:{item}")
      Output:
      1:a
      2:b
      3:c

    • Using zip() to iterate over multiple lists
      x = [1, 2]
      y = ["a", "b"]
      z = ["A", "B"]
      for i, j, k in zip(x, y, z):
        print(f"{i}:{j}:{k}")
      Output:
      1:a:A
      2:b:B
  8. List Comprehensions
    • List comprehensions
      # traditional approach
      y = []
      for x in range(1, 3):
        y.append(x ** 2)
      print(y) # Output: [1, 4]
      
      # list comprehension
      z = [(x ** 2) for x in range(1, 3)]
      print(z) # Output: [1, 4]

    • List comprehension with conditional filtering
      w = [(x ** 2) for x in range(1, 3) if x % 2 == 0]
      print(w) # Output: [4]

    • List comprehension with conditional expression
      w = [1, -2]
      z = [x if x >=0 else -x for x in w]
      print(z) # Output: [1, 2]

    • List comprehension with string methods
      w = ['a', 'b']
      z = [x.upper() for x in w]
      print(z) # Output: ['A', 'B']

    • Nested list comprehension
      x = [[1, 2], [3, 4]]
      y = [row for row in x]
      print(y) # Output: [[1, 2], [3, 4]]
      flattened = [num for row in x for num in row]
      print(flattened) # Output: [1, 2, 3, 4]
  9. Slicing & Copying
    • Slicing a list ([start:end:step])
      x = [0, 1, 2, 3, 4, 5]
      You can specify the index of the first item (inclusive) and the last item (exclusive):
      print(x[1:3]) # Output: [1, 2]
      You can skip the index of the first item (defaults to 0)
      print(x[:4]) # Output: [0, 1, 2, 3]
      You can skip the index of the last item (defaults to the length of the list):
      print(x[3:]) # Output: [3, 4, 5]
      You can skip the index of the first and last item (useful to copy a list): index of the first item default to 0 and the last defaults to the length of the list
      print(x[:]) # Output: [0, 1, 2, 3, 4, 5]
      To get the slice of the last items, you can use a negative index:
      print(x[-3:]) # Output: [3, 4, 5]
      print(x[:-3]) # Output: [0, 1, 2]
      You can decide how many items to skip between items in the specified range by setting a third index in the brackets:
      print(x[0:6:2]) # Output: [0, 2, 4]
      
      # first:last:step=2
      print(x[::2]) # Output: [0, 2, 4]
      
      # reverse slicing
      print(x[::-1]) # Output: [5, 4, 3, 2, 1, 0]
      print(x[::-2]) # Output: [5, 3, 1]

    • Looping through a slice
      for y in x[0:6:2]:
        print(y)
      Output:
      0
      2
      4

    • Copying lists
      x = [1, 2, [3, 4]]
      Copy by reference:
      y = x # both x and y reference the same list
      y[0] = 0
      print(x[0]) # Output: 0
      Copy by value:
      Basic types don't affect the original values.
      Nested objects are still references to the items in the original list and hence updates affect the original value.
      Replacing the entire nested object reference does NOT affect the original object.
      y = x[:] # new copy but nested objects are still references to the items in the original list
      z = x.copy() # new copy but nested objects are still references to the items in the original list
      w = list(x) # new copy but nested objects are still references to the items in the original list
      y[0] = 'a'
      z[0] = 'b'
      w[0] = 'c'
      print(x[0]) # Output: 0
      print(y[0]) # Output: a
      print(z[0]) # Output: b
      print(w[0]) # Output: c
      
      # replacing the entire nested object reference does NOT affect the original object
      y[2] = [6, 7]
      print(x[2]) # Output: [3, 4]
      
      # nested objects are references and hence updates affect the original value
      z[2][1] = 5
      print(x[2]) # Output: [3, 5]
      Deep copy: create complete new list including nested objects
      import copy
      y = copy.deepcopy(x)
      y[2] = ['a', 'b']
      print(x[2]) # Output: [3, 5]
      print(y[2]) # Output: ['a', 'b']
  10. Other Lists functions
    x = [1, 2, 0, 9, 8, 7]
    
    # length
    print(len(x)) # Output: 6
    
    # min
    print(min(x)) # Output: 0
    
    # max
    print(max(x)) # Output: 9
    
    # sum
    print(sum(x)) # Output: 27
    
    # counting occurrences of an element
    print(x.count(9)) # Output: 1
    
    # check if all elements are true (0 isn't)
    print(all(x)) # Output: False
    
    # check if all elements are true with conditions
    print(all(i > 1 for i in x)) # Output: False
    
    # check if any element is true
    print(any(x)) # Output: True
    
    # check if any element is true with conditions
    print(any(i > 1 for i in x)) # Output: True
© 2025  mtitek