Lists in Python

The list is a most versatile data type available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.

The first index is zero, the second index is one, and so forth.

Example of a list:

  • list1 = [‘physics’, ‘chemistry’, 1997, 2000]
  • list2 = [1, 2, 3, 4, 5 ]

The items in a list are mutable meaning that they can be later changed as the program runs.

From the above example, if we wish to change the item in list1, in index 1 from “Physics” to “Math”, we can use the code:

  • list1[1] = “blackcurrant”
  • print(list1)
    • Gives output: [‘Math’,’chemistry’,1197,2000]

We can use many methods in lists to get the number of elements, to join the lists, add new values and more.

  • len() can be used to find the number of elements in a list.
    • list1 = [‘hello’, ‘world’]
    • print(len(list1))
      • Gives output: 2 as there are 2 elements in the list.
  • append() can be used to add an item to the end of the list.
    • odd = [1, 3, 5]
    • odd.append(7)
    • print(odd)
      • Gives output: [1,3,5,7]
  • + can be used to concatenate items into a list.
    • odd = [1, 3, 5]
    • print(odd + [9, 7, 5])
      • Gives output: [1, 3, 5, 9, 7, 5]

We can uses indexes to return or remove elements from the list as well.

  • thislist = [“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”]
  • print(thislist[2:])
    • Gives output: [‘cherry’, ‘orange’, ‘kiwi’, ‘melon’, ‘mango’]
  • Using a negative index will give us the last element.
  • thislist = [“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”]
  • print(thislist[-1])
    • Gives output: [‘kiwi’]

Leave a Reply

Your email address will not be published. Required fields are marked *