Lists

Lists are the most versatile datatype available in Python and can be written as a collection of comma-separated values (items) between square brackets.

An advantage of using lists is that you can store multiple items of different types within a single variable. Lists are also one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Creating a List


          # Create an empty list
          nums = []

          # Adding values to the list
          nums.append(1)
          nums.append(2)
          nums.append(3)
          nums.append(4)
          
          print(nums)
          >>> [1, 2, 3, 4]


          # You can also initialize a list with values
          nums = [1, 2, 3, 4]

          print(nums)
          >>> [1, 2, 3, 4]


          # The * operator can be used to create repeated lists 
          nums = [1, 2, 3] * 3
          
          print(nums)
          >>> [1, 2, 3, 1, 2, 3, 1, 2, 3]


          # The range() function can also be used to generate a list of numbers
          # The parameters of the range() function are: 
          #  start: Starting number
          #  stop: Ending number (non-inclusive)
          #  step_size: How much to increment with each step, defaults to 1 if not provided

          nums = list(range(10)) 

          print(nums)
          >>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


          nums = list(range(10, 15))

          print(nums)
          >>> [10, 11, 12, 13, 14]


          nums = list(range(2, 20, 2))

          print(nums)
          >>> [2, 4, 6, 8, 10, 12, 14, 16, 18]


          # Lists can also contain different data types
          myList = [5, "Hello", 3.14, True]


          # Creating a list of lists (2D / Nested lists) 
          myList = [["Faizan", 2], ["John", 5], ["Steve", 6]]
        

Accessing List Elements


          # Accessing specific elements
          
          nums = [10, 20, 30, 40, 50, 60]

          firstNum = nums[0] # First element
          print(firstNum)
          >>> 10

          lastNum = nums[-1] # Last element
          print(lastNum)
          >>> 60


          # Accessing multiple elements (slicing)

          nums = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

          first3 = nums[0 : 3]

          print(first3)
          >>> [5, 10, 15]


          elements5ToEnd = nums[4 : ]

          print(elements5ToEnd)
          >>> [25, 30, 35, 40, 45, 50]


          last3 = nums[-3 : ]

          print(last3)
          >>> [40, 45, 50]

          
          # Accessing elements in 2D Lists

          myList = [["Faizan", 2], ["John", 5], ["Steve", 6], ["Mike", 9]]
          
          firstElementName = myList[0][0]
          print(firstElementName)
          >>> Faizan

          lastElementName = myList[-1][0]
          print(lastElementName)
          >>> Steve
        

Adding / Modifying List Elements


          # Changing specific elements
          
          nums = [10, 20, 30, 40, 50, 60]

          nums[0] = 5 
          nums[3] = 20 

          print(nums)
          >>> [5, 20, 30, 20, 50, 60]


          # Changing multiple elements

          nums = [10, 11, 12, 13, 14, 15]

          # From elements 1 to 3, not including 4
          nums[1 : 4] = [50, 51, 52] 

          print(nums)
          >>> [10, 50, 51, 52, 14, 15]
          

          # Adding singular elements to a list is done through the append() function

          nums = [1, 2, 3, 4, 5]

          nums.append(6)

          print(nums)
          >>> [1, 2, 3, 4, 5, 6]

          
          # Inserting elements at a specific index

          nums = [10, 20, 30, 40, 50]

          # Insert 25 at index 2
          nums.insert(2, 25) 

          print(nums)
          >>> [10, 20, 25, 30, 40, 50]
        

Combining Lists


          # If you want to combine two lists, use the extend() function 

          nums1 = [1, 2, 3, 4, 5, 6]
          nums2 = [7, 8, 9, 10]

          nums1.extend(nums2)

          print(nums1)
          >>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


          # You can also combine two lists using the + operator (concatenation)

          list1 = [1, 2, 3, 4, 5]
          list2 = [6, 7, 8, 9, 10]
          
          combinedList = list1 + list2

          print(combinedList)
          >>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        

Deleting / Removing List Elements


          # Deleting a specific element 

          nums = [10, 11, 12, 13, 14, 15]
          
          del nums[2] # Delete the element at index 2

          print(nums)
          >>> [10, 11, 13, 14, 15]


          # Deleting multiple elements
          
          nums = [10, 11, 12, 13, 14, 15]
          
          del nums[2 : 5] # Delete elements from indexes 2 to 4, not including 5

          print(nums)
          >>> [10, 11, 15]


          # Delete an entire List
          del nums 


          # Removing a specific element 

          myList = ['S', 'J', 'U', 'S', 'A', 'T', 'A']

          myList.remove('U')

          print(myList)
          >>> ['S', 'J', 'S', 'A', 'T', 'A']


          # You can also use the pop() function to remove an item at a given index. 
          # The pop() function removes and returns the last item if the index is not provided
          # This helps us implement lists as stacks (first in, last out data structure)
         
          myList = ['H', 'E', 'L', 'L', 'O']

          secondElement = myList.pop(1)
          
          print(secondElement)
          >>> E

          print(myList)
          >>> ['H', 'L', 'L', 'O']


          lastElement = myList.pop()

          print(lastElement)
          >>> O

          print(myList)
          >>> ['H', 'L', 'L']
    

          # Empty a list

          myList = ['S', 'A', 'T', 'A']

          myList.clear()

          print(myList)
          >>> []
        

Counting the Number of Occurences of a List Element


          # The count() function returns the number of times the specified element appears in the list

          myList = ['S', 'J', 'U', 'S', 'A', 'T', 'A']

          count = myList.count('S')
          
          print(count)
          >>> 2

          count = myList.count('I')

          print(count)
          >>> 0
        

Finding the Index of List Elements


          # The index() function returns the index of the specified element in the list
          # The index() function only returns the index of the first occurrence of the matching element

          myList = ['S', 'J', 'U', 'S', 'A', 'T', 'A']

          index = myList.index('J')
          
          print(index)
          >>> 1

          index = myList.index('S')

          print(index)
          >>> 0

          index = myList.index('P')
          >>> ValueError: 'P' is not in list


          # The index() function can also take a maximum of three arguments:
          # element - the element to be searched
          # start (optional) - start searching from this index
          # end (optional) - search the element up to this index

          myList = ['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']

          index = myList.index('O', 5) # Start searching from index 5 to the end 

          print(index)
          >>> 6

          index = myList.index('L', 1, 5)

          print(index)
          >>> 2
        

Sorting Lists


          # There are two ways of sorting lists in python:
          # The sort() function modifies the original list, arranging the elements in 
          # ascending or descending order
          
          # By default, sort() doesn't require any parameters. However, it has two optional parameters:
          # reverse - If True, the sorted list is reversed (or sorted in Descending order)
          # key - function that serves as a key for the sort comparison

          myList = [100, 32, 89, 12, 56, 24, 78]

          myList.sort()
          
          print(myList)
          >>> [12, 24, 32, 56, 78, 89, 100]

          myList.sort(reverse = True)

          print(myList)
          >>> [100, 89, 78, 56, 32, 24, 12]


          # Sorting by alphabetical order

          myList = ['S', 'J', 'U', 'S', 'A', 'T', 'A']
          
          myList.sort()
          
          print(myList)
          >>> ['A', 'A', 'J', 'S', 'S', 'T', 'U']


          # Python also has a built-in sorted() function for the same purpose
          # The sorted() function does not change the original list, instead it returns the sorted List

          myList = [34, 23, 90, 12, 67, 54, 76]

          sortedList = sorted(myList)

          print(sortedList)
          >>> [12, 23, 34, 54, 67, 76, 90]
          
          print(myList)
          >>> [34, 23, 90, 12, 67, 54, 76]


          # The reverse parameter can also be used to sort by descending order 

          reversedSortedList = sorted(myList, reverse = True)

          print(reversedSortedList)
          >>> [90, 76, 67, 54, 34, 23, 12]


          # Sorting based on the length of each element

          myList = ['Hello', 'I', 'Hope', 'This', 'Website', 'Is', 'Useful']

          myList.sort(key=len)

          print(myList)
          >>> ['I', 'Is', 'Hope', 'This', 'Hello', 'Useful', 'Website']


          # Sorting 2D Lists

          studentTestScores = [['Mike', 90], 
                               ['Chris', 76],
                               ['Steve', 92],
                               ['Dave', 85],
                               ['Bill', 72]] 
              

          # Sort by the 2nd element in each list
          studentTestScores.sort(reverse = True, key = lambda x : x[1])
          
          print(studentTestScores)
          >>> [['Steve', 92], ['Mike', 90], ['Dave', 85], ['Chris', 76], ['Bill', 72]]



          # Sorting a list of dictionaries 

          employees = [
              {'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
              {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
              {'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
              {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
          ]
          

          # Sort by Name (Ascending order)
          employees.sort(key = lambda x: x.get('Name'))
          
          print(employees)
          >>> [{'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
               {'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, 
               {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, 
               {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}]
          


          # Sort by Age (Ascending order)
          employees.sort(key = lambda x: x.get('age'))
          
          print(employees)
          >>> [{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
               {'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, 
               {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
               {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}]



          # The sorted() function can be used in the same way, without changing the original list

          sortedBySalaries = sorted(employees, reverse = True, key = lambda x : x.get("salary"))

          print(sortedBySalaries)
          >>> [{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
               {'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, 
               {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, 
               {'Name': 'John Hopkins', 'age': 18, 'salary': 1000}]
        

Checking List Membership


          # Python makes it very easy to check if a particular element is in a list
          
          myList = ['S', 'J', 'U', 'S', 'A', 'T', 'A']

          print('A' in myList)
          >>> True

          print('P' in myList)
          >>> False


          nums = [10, 20, 30, 40, 50]

          print(10 in nums)
          >>> True


          # You can also check if an element is not in a List

          reviews = ['Good', 'Great', 'Excellent']

          print('Bad' not in reviews)
          >>> True

          
          nums = [1, 2, 3, 4, 5, 6, 7, 8]
          
          print(10 not in nums)
          >>> True
        

Iterating Over Lists


          # There are two main ways to iterate over Lists

          # Iterating over each element by index

          nums = [5, 10, 15, 20, 25]
          
          for x in range(len(nums)):
            print(nums[x])

          >>> 5
              10
              15
              20
              25


          # Or you can directly access each element in the list like this:

          for x in nums:
            print(x)

          >>> 5
              10
              15
              20
              25 
          

          # You can also use the enumerate() function to access each element and its corresponding index 

          myList = ['H', 'E', 'L', 'L', 'O']

          for index, element in enumerate(myList):
            print(index, element)

          >>> 0 H
              1 E
              2 L
              3 L
              4 O


          # The zip() function can also be used to easily iterate over two lists at once

          list1 = ['H', 'E', 'L', 'L', 'O']
          list2 = ['W', 'O', 'R', 'L', 'D']

          # Here, l1 represents the corresponding element from list1 
          # l2 represents the corresponding element from list2

          for l1, l2 in zip(list1, list2):
            print(l1, l2)
          
          >>> H W
              E O
              L R
              L L
              O D

          
          # Another example using the zip() function

          words1 = ['laptop', 'phone', 'speaker', 'camera']
          words2 = ['book', 'pen', 'marker', 'eraser']
          
          for w1, w2 in zip(words1, words2):
          
              print(w1, w2)

          >>> laptop book
              phone pen
              speaker marker
              camera eraser


          # Iterating over a 2D list

          stockPrices = [['AAPL', 125],
                         ['MSFT', 250],
                         ['PYPL', 260],
                         ['NVDA', 620]]
               

          for row in range(len(stockPrices)):
              
            for col in range(len(stockPrices[row])): 
                  
                print(stockPrices[row][col], end = ' ')
                  
            print()

          >>> AAPL 125 
              MSFT 250 
              PYPL 260 
              NVDA 620 

          
          # Or simply:

          for row in stockPrices:
    
              for item in row: 
                
                  print(item, end = ' ')
                
            print()

          >>> AAPL 125 
              MSFT 250 
              PYPL 260 
              NVDA 620 
        

List Comprehension


          # List comprehension is a short and concise way to create a list 

          powersOf2 = [2 ** x for x in range(10)] # All powers of 2 from 2^0 to 2^9

          print(powersOf2)
          >>> [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]


          # The code above is equivalent to:

          powersOf2 = []
          for x in range(10):
            powersOf2.append(2 ** x)


          # More examples of list comprehension

          name = 'Faizan'

          nameLetters = [letter for letter in name]
          
          print(nameLetters)
          >>> ['F', 'a', 'i', 'z', 'a', 'n']


          listOfWords = ['Computer', 'Science', 'is', 'Life']

          items = [word[0] for word in listOfWords] # Returns a list containing the first letter of each word in listOfWords

          print(items)
          >>> ['C', 'S', 'i', 'L']


          # You can also include if conditionals within a list comprehension

          prices = [50, 35, 89, 65, 23, 54, 32, 48, 73]

          pricesAbove50 = [x for x in prices if x > 50]

          print(pricesAbove50)
          >>> [89, 65, 54, 73]

          
          sentence = 'The rocket came back from mars'
          
          vowels = [i for i in sentence if i in 'aeiou'] # Returns a list of all the vowels in the sentence
          
          print(vowels)
          >>> ['e', 'o', 'e', 'a', 'e', 'a', 'o', 'a']


          oddNums = [x for x in range(20) if x % 2 == 1]
          
          print(oddNums)
          >>> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
        

Mapping and Filtering Lists


          # The map() function can be used to apply a function to each element in a list
          # Syntax: map(function, iterable)

          def squared(n):
            return n ** 2
      
          nums = [1, 2, 3, 4, 5]

          squaredNums = list(map(squared, nums))

          print(squaredNums)
          >>> [1, 4, 9, 16, 25]


          # Lambda expressions can also be used to achieve the same result

          squaredNums2 = list(map(lambda x: x ** 2, nums))

          print(squaredNums2)
          >>> [1, 4, 9, 16, 25]


          # More examples of using the map() function

          negativeNums = [-92, -34, -54, -21, -45, -74]

          absNums = list(map(abs, negativeNums)) # abs() is the absolute value function

          print(absNums)
          >>> [92, 34, 54, 21, 45, 74]


          words = ["processing", "strings", "with", "map"]

          capitalizedWords = list(map(str.capitalize, words))

          print(capitalizedWords)
          >>> ['Processing', 'Strings', 'With', 'Map']


          # Filtering Lists

          scores = [74, 63, 86, 95, 50, 82, 91, 68]
          
          scoresAbove70 = list(filter(lambda score: score >= 70, scores))

          print(scoresAbove70)
          >>> [74, 86, 95, 82, 91]


          words = ['sky', 'cloud', 'wood', 'forest', 'tie', 'nice', 'cup', 'trees']

          wordsLen3 = list(filter(lambda s: len(s) == 3, words))

          print(wordsLen3)
          >>> ['sky', 'tie', 'cup']