Python lists

  • The data type list is an ordered sequence which is mutable and made up of one or more elements.
  • List can have elements of different data types, such as integer, float, string, tuple or even another list.
  • List is very useful to group together elements of mixed data types.

sytanx - Example

names = ["Krishna", "Arjun", "Kausalya"]

access list item with index

  • As list is an ordered sequence we can access the elements with an index
  • Index starts with 0 and ends with length of list - 1
  • List supports negative index which starts from -1 (i.e -1, -2, -3, ...)
names = ["Krishna", "Arjun", "Kausalya"]
name = names[1]
print(name)
# Output: Arjun

slicing a list

  • we can get a part or a slice of a list with slicing
  • slice syntax: mylist[start:end:step]
  • start is start index position. default is 0
  • end is the end index exclusive. default is length of list - 1
  • step is current index + number.
  • Try out the below code to see how it works
numbers = [1,2,3,4,5,6,7,8,9,0]
print(numbers[1:5])
# Output: [2, 3, 4, 5]
print(numbers[5:])
# Output: [6, 7, 8, 9, 0]
print(numbers[:5])
# Output: [1, 2, 3, 4, 5]
print(numbers[0:9:2])
# Output: [1, 3, 5, 7, 9]

check if element exists in a list

  • we use in operator to check if element exists
names = ["Krishna", "Arjun", "Kausalya"]
print("Anji" in names)
# Output: False

check if element not exists in a list

  • use not in operator to check if element exists
names = ["Krishna", "Arjun", "Kausalya"]
print("Anji" not in names)
# Output: True

update list element with an index

fruits = ["apple", "banana", "cherry"]
fruits[0] = "watermelon"
print(fruits)
# Output: ['watermelon', 'banana', 'cherry']

update a range of elements

numbers = [1,2,3,4,5,6,7,8,9]
numbers[0:5] = [100, 200, 300, 400, 500, 600]
print(numbers)
# Output: [100, 200, 300, 400, 500, 600, 6, 7, 8, 9]

insert an element at an index

  • use method insert() to add an element at a specific index.
fruits = ["apple", "banana", "cherry"]
fruits.insert(2, "watermelon")
print(fruits)
# Output: ['apple', 'banana', 'watermelon', 'cherry']

add an element to end of the list

  • use method append() to add an element at the end of the list
names = ["Anji", "Arun", "Abhi"]
names.append("John")
print(names)
# Output: ['Anji', 'Arun', 'Abhi', 'John']

append multiple elements to the list

  • use method extend() to add all elements from one list to other
  • we can any iterable with extend() method like tuple, set, etc.
games = ["I spy", "Hide-and-seek", "Musical chairs"]
outdoor_games = ["Kho-kho", "Football", "Volleyball"]
games.extend(outdoor_games)
print(games)
# Output: ['I spy', 'Hide-and-seek', 'Musical chairs', 'Kho-kho', 'Football', 'Volleyball']

remove an element from list

  • use method list.remove(element) to remove an element
numbers = [1,2,3,"remove me",5,6]
numbers.remove("remove me")
print(numbers)
# Output: [1, 2, 3, 5, 6]

remove an element at an index from list

  • use method list.pop(index) to delete element at an index
numbers = [1,2,3,4,5]
index = 2
numbers.pop(index)
print(numbers)
# Output: [1, 2, 4, 5]
  • If index is not given then it will remove the last element.
numbers = [1,2,3,4,5]
numbers.pop()
print(numbers)
# Output: [1, 2, 3, 4]

empty a list

  • use method list.clear() to delete all elements from the list.
fruits = ["apple", "banana"]
fruits.clear()
print(fruits)
# Output: []

using for loop with list

fruits = ["apple", "banana"]
for fruit in fruits:
    print(fruit)
# Output:
# apple
# banana

list comprehension

  • List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list or any iterable element.
numbers = [1,2,3,4,5]
squares = [num * num for num in numbers]
print(squares)
# Output: [1, 4, 9, 16, 25]

conditional list comprehension

  • list comprehension to filter names start with letter "A"
names = ["Anji", "Ram", "Arun"]
names_list = [name for name in names if name.startswith("A")]
print(names_list)
# Output: ['Anji', 'Arun']
  • list comprehension to convert names to upper case if it starts with "A"
names = ["Anji", "Naveen", "Arun"]
names_list = [name.upper() if name.startswith("A") else name for name in names]
print(names_list)
# Output: ['ANJI', 'Naveen', 'ARUN']

sort elements of a list

  • list sorting can be done in two ways
  • by using list method list.sort()
  • by using builtin function sorted(list)

  • list.sort() in an inplace sort which modifies the list.

numbers = [3,2,4,5,1]
numbers.sort()
print(numbers)
# Output: [1, 2, 3, 4, 5]
  • sorted(list) is not an inplace sort which sorts list elements and returns a new list.
numbers = [3,2,4,5,1]
new_list = sorted(numbers)
print(new_list)
# Output: [1, 2, 3, 4, 5]
print(numbers)
# Output: [3,2,4,5,1]

copy existing list to other

  • use list.copy() method to copy list object
numbers = [1,2,3,4,5]
numbers_copy = numbers.copy()
print(numbers_copy)
# Output: [1,2,3,4,5]
  • alternative is to use list constructor
numbers = [1,2,3,4,5]
numbers_copy = list(numbers)
print(numbers_copy)
# Output: [1,2,3,4,5]

combine two lists with + operator

letters = ["a", "b", "c"]
numbers = [1,2,3,4]
chars = letters + numbers
print(chars)
# Output: ['a', 'b', 'c', 1, 2, 3, 4]

other useful list methods

  • python has a set of built-in methods that we can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Read more about list at official docs

References