Python List

What is a List in Python?

A list is a data type in Python where you can store multiple values of different data types (including nested lists).

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

stringList = ["banana", "orange", "apple"]

mixedList = [1, "banana", "orange", [5, 6]]

You can access items in a list using their index position. Index positions start from 0 in lists:

stringList = ["banana", "orange", "apple"]

print(stringList[1])
# "orange"

another example

li = ['a', 0, 1.234]
# ['a', 0, 1.234]

li.append(True)
# ['a', 0, 1.234, True]

li[0]
# 'a'

li[-1]
# True

li[1:3]
# [0, 1.234]

li[2:]
# [1.234, True]

li[:2]
# ['a', 0]

li[-3:-1]
# [0, 1.234]
li = [1,2,3]
li.append(4)
print(li)
li.pop()
print(li)
li.pop(0)
print(li)
# [1, 2, 3, 4]
# [1, 2, 3]
# [2, 3]
li = [1,2,3]
print(3 in li)
print(4 in li)
# True
# False
nested = [1,2,['a','b']]
# [1, 2, ['a', 'b']]

nested[2]
# ['a', 'b']

nested[2][1]
# 'b'

How to Sort Lists in Python

You can sort a list in Python using the sort() method.

The sort() method allows you to order items in a list. Here’s the syntax:

list.sort(reverse=True|False, key=sortFunction)

By default, you can order strings and numbers in ascending order, without passing an argument to this method:

items = ["orange", "cashew", "banana"]

items.sort()
# ['banana', 'cashew', 'orange']

For descending order, you can pass the reverse argument:

items = [6, 8, 10, 5, 7, 2]

items.sort(reverse=True)
# [10, 8, 7, 6, 5, 2]

How to specify a sort function

items = [
  {
    'name': 'John',
    'age': 40
  },
  {   
    'name': 'Mike',
    'age': 45
  },
  {   
    'name': 'Jane',
    'age': 33
  },
  {   
    'name': 'Asa',
    'age': 42
  }
]

def sortFn(dict):
  return dict['age']

items.sort(key=sortFn)
# [
#   {'name': 'Jane', 'age': 33},
#   {'name': 'John', 'age': 40},
#   {'name': 'Asa', 'age': 42},
#   {'name': 'Mike', 'age': 45}
# ]

If the reverse argument is passed as True here, the sorted dictionaries will be in descending order.

items = ["cow", "elephant", "duck"]

def sortFn(value):
    return len(value)

items.sort(key=sortFn, reverse=True)
# ['elephant', 'duck', 'cow']