Skip to content

Lists

A list in Python is an ordered collection of items (or elements), which can be of different data types (integers, strings, floats, etc.).

Lists are mutable, meaning you can change their content (add, remove, modify elements) after they are created.

Lists in Python Programming
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "Python", 3.14, [2, 3, 4]]

fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
print(type(fruits)) # Output: <class 'list'>

Just like string, we can also use negative indexing to access elements from the end of the list like this:

print(fruits[-1]) # Output: cherry

We can extract portions (or slices) of a list by specifying a range of indices using the slicing syntax: list[start:end:step].

numbers = [1, 2, 3, 4, 5, 6, 7]
# Slicing
print(numbers[1:4]) # Output: [2, 3, 4]
# Slicing with a step
print(numbers[::2]) # Output: [1, 3, 5, 7]
# Reverse the list
print(numbers[::-1]) # Output: [7, 6, 5, 4, 3, 2, 1]

  • len(): Returns the number of elements in a list.
  • min(): Returns the smallest element in a list.
  • max(): Returns the largest element in a list.
  • sum(): Returns the sum of elements in a numeric list.
  • sorted(): Returns a new list with elements sorted.
numbers = [3, 1, 4, 1, 5, 9]
print(len(numbers)) # Output: 6
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 9
print(sum(numbers)) # Output: 23
print(sorted(numbers))#Output: [1, 1, 3, 4, 5,9]

  • append(): Adds an element at the end of the list.
  • clear(): Removes all elements from the list.
  • copy(): Returns a shallow copy of the list.
  • count(): Returns the number of elements with the specified value.
  • extend(): Adds the elements of an iterable (like another list) to the end of the current list.
  • index(): Returns the index of the first element with the specified value.
  • insert(): Adds an element at a specified position.
  • pop(): Removes the element at a specified position (or the last element if no index is specified).
  • remove(): Removes the first occurrence of the specified value.
  • reverse(): Reverses the order of the list in place.
  • sort(): Sorts the elements of the list in ascending order by default (can take a custom key).
my_list = [3, 1, 4, 1, 5, 9, 2]
# append()
my_list.append(6)
print("After append:",my_list)#[3, 1, 4, 1, 5, 9, 2,6]
# clear()
copy_list = my_list.copy()
copy_list.clear()
print("After clear:", copy_list) # []
# copy()
copied_list = my_list.copy()
print("Copy of list:",copied_list)#[3, 1, 4, 1, 5, 9,2,6]
# count()
count_1 = my_list.count(1)
print("Count of 1:", count_1) # 2
# extend():
my_list.extend([7, 8, 9])
print("After extend:",my_list)# [3,1,4,1,5,9,2,6, 7,8,9]
# index():
index_5 = my_list.index(5)
print("Index of 5:", index_5) # 4
# insert():
my_list.insert(2, 10)
print("After insert:",my_list)#[3,1,10,4,1,5,9,2,6,7,8,9]
# pop():
popped_element = my_list.pop()
print("After pop:", my_list)#[3,1,10,4,1,5,9, 2, 6, 7, 8]
print("Popped element:", popped_element) # 9
# remove():
my_list.remove(10)
print("After remove:", my_list)#[3,1,4,1,5,9,2, 6, 7, 8]
# reverse():
my_list.reverse()
print("After reverse:", my_list)#[8,7,6,2,9,5,1,4, 1, 3]
# sort()
my_list.sort()
print("After sort:", my_list)#[1,1,2,3,4,5,6,7,8,9]
# sort() with reverse=True
my_list.sort(reverse=True)
print("reverse sort:",my_list)#[9,8,7,6,5,4,3, 2,1,1]

The above list methods are the methods which are used mostly by python programmers.

There are a whole lot of other methods that python provides which can always be referred from the python docs: Python Lists Methods


List comprehension is a concise way to create new lists from existing sequences. It provides a more readable and efficient alternative to a traditional for loop and conditional statements. The basic structure is [expression for item in iterable if condition].


  • expression: The value to be included in the new list. This can be the item itself or a modified version of it.
  • item: The variable representing each element in the iterable.
  • iterable: Any sequence you can loop through, such as a list, tuple, or a range.
  • if condition (optional): A filter that includes only items for which the condition is True.

  • Filtering Items You can use a list comprehension to filter items based on a condition, which is a common task. For example, to find all fruits in a list that contain the letter “a”:

    fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
    newlist = [x for x in fruits if "a" in x]
    # Output: ['apple', 'banana', 'mango']
  • Manipulating Items The expression part of the syntax allows you to transform items as they’re added to the new list. For example, you can convert all fruits to uppercase:

    fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
    newlist = [x.upper() for x in fruits]
    # Output: ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
  • Creating Lists of Pairs You can use nested loops within a list comprehension to create lists of pairs, which is a powerful application. For instance, to generate a list of all coordinate pairs (x, y) from a specified range:

    coords = [(x, y) for x in range(3) for y in range(3)]
    # Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]