Lists in Python

Index

  1. Definition
  2. Creating a list
  3. Operations on Lists
  4. Built-in Functions on Lists
  5. Implementation of Stacks and Queues using Lists
  6. Nested Lists

Definition

Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data

All the items in a list are assigned to a single variable.

Lists avoid having a separate variable to store each item which is less efficient and more error prone when you have to perform some operations on these items.

Lists can be simple or nested lists with varying types of values.

Lists are one of the most flexible data storage formats in Python because they can have values added, removed, and changed.

You can store any item in a list like string, number, object, another variable and even another list. You can have a mix of different item types and these item types need not have to be homogeneous. For example, you can have a list which is a mix of type numbers, strings and another list itself.

You can create an empty list without any items. The syntax is, list_name = [ ]

Creating a list

Lists are constructed using square brackets [ ] wherein you can include a list of items separated by commas.

Syntax for creating a list:

list_name = [item_1, item_2, item_3, ......., item_n]

Example:

>>> superstore = ["metro", "tesco", "walmart", "kmart", "carrefour"]
>>> superstore
//output
		['metro', 'tesco', 'walmart', 'kmart', 'carrefour']

Operations on Lists

Basic operations on lists

The different operations of list are

  • Repetition
  • Concatenation
  • Length
  • Iteration
  • Membership

In Python, lists can also be concatenated using the + sign, and the * operator is used to create a repeated sequence of list items. For example,

>>> list_1 = [1, 3, 5, 7]
>>> list_2 = [2, 4, 6, 8]
>>> list_1 + list_2
 [1, 3, 5, 7, 2, 4, 6, 8]
>>> list_1 * 3
 [1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]
>>> list_1 == list_2
 False

len() is used to get the length of the list

>>> list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
>>> len(list1)
	9

The for loop is used to iterate over the list elements.

>>> # iteration of the list
>>> # declaring the list
>>> list1 = [12, 14, 16, 39, 40]
>>> # iterating
>>> for i in list1:
>>> print(i)
	12
	14
	16
	39
	40

You can check for the presence of an item in the list using in and not in membership operators. It returns a Boolean True or False. For example,

>>> list_items = [1,3,5,7]
>>> 5 in list_items
 True
>>> 10 in list_items
 False

The list() Function

The built-in list() function is used to create a list. The syntax for list() function is, list([sequence])

>>> quote = "How you doing?"
>>> string_to_list = list(quote)
>>> string_to_list
 ['H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']
>>> friends = ["j", "o", "e", "y"]
>>> friends + quote
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 TypeError: can only concatenate list (not "str") to list
>>> friends + list(quote)
 ['j', 'o', 'e', 'y', 'H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']

Built-in Functions on Lists

There are many built-in functions for which a list can be passed as an argument

Built-In FunctionsDescription
len()The len() function returns the numbers of items in a list.
sum()The sum() function returns the sum of numbers in the list.
any()The any() function returns True if any of the Boolean values in the list is True.
all()The all() function returns True if all the Boolean values in the list are True, else returns False.
sorted()The sorted() function returns a modified copy of the list while leaving the original list untouched.
max() & min()Returns the maximum and minimum elements present in the string

For example,

>>> lakes = ['superior', 'erie', 'huron', 'ontario', 'powell']
>>> len(lakes)
 5
>>> numbers = [1, 2, 3, 4, 5]
>>> sum(numbers)
 15
>>> max(numbers)
 5
>>> min(numbers)
 1
>>> any([1, 1, 0, 0, 1, 0])
 True
>>> all([1, 1, 1, 1])
 True
>>> lakes_sorted_new = sorted(lakes)
>>> lakes_sorted_new
 ['erie', 'huron', 'ontario', 'powell', 'superior']

Implementation of Stacks and Queues using Lists

List methods

The list size changes dynamically whenever you add or remove the items

Various List Methods

List MethodsSyntaxDescription
append()list.append(item)The append() method adds a single item to the end of the list. This
method does not return new list and it just modifies the original.
count()list.count(item)The count() method counts the number of times the item has
occurred in the list and returns it.
insert()list.insert(index, item)The insert() method inserts the item at the given index, shifting
items to the right.
extend()list.extend(list2)The extend() method adds the items in list2 to the end of the list.
index()list.index(item)The index() method searches for the given item from the start of
the list and returns its index. If the value appears more than once,
you will get the index of the first one. If the item is not present in
the list then ValueError is thrown by this method.
remove()list.remove(item)The remove() method searches for the first instance of the given
item in the list and removes it. If the item is not present in the list
then ValueError is thrown by this method.
sort()list.sort()The sort() method sorts the items in place in the list. This method
modifies the original list and it does not return a new list.
reverse()list.reverse()The reverse() method reverses the items in place in the list. This
method modifies the original list and it does not return a new list.
pop()list.pop([index])The pop() method removes and returns the item at the given index.
This method returns the rightmost item if the index is omitted.

For example,

>>> cities = ["oslo", "delhi", "washington", "london", "seattle", "paris", "washington"]
>>> cities.count('seattle')
 1
>>> cities.index('washington')
 2
>>> cities.reverse()
>>> cities
 ['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo']
>>> cities.append('brussels')
>>> cities
 ['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo', 'brussels']
>>> cities.sort()
>>> cities
 ['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'washington']
>>> cities.pop()
 'washington'
>>> cities
 ['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington']
>>> more_cities = ["brussels", "copenhagen"]
>>> cities.extend(more_cities)
>>> cities
 ['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'brussels', 'copenhagen']
>>> cities.remove("brussels")
>>> cities
 ['delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'brussels', 'copenhagen']

Nested Lists

A list inside another list is called a nested list and you can get the behavior of nested lists in Python by storing lists within the elements of another list. You can traverse through the items of nested lists using the for loop.

The syntax for nested lists is,

nested_list_name = [[item_1],[item_2],[item_3],
										[item_4],[item_5],[item_6],
										[item_7], [item_8], [item_9]]

Each list inside another list is separated by a comma. For example,

>>> asia = [["India", "Japan", "Korea"],
						["Srilanka", "Myanmar", "Thailand"],
						["Cambodia", "Vietnam", "Israel"]]
>>> asia[0]
 ['India', 'Japan', 'Korea']
>>> asia[0][1]
 'Japan'
>>> asia[1][2] = "Philippines"
>>> asia
 [['India', 'Japan', 'Korea'], ['Srilanka', 'Myanmar', 'Philippines'], ['Cambodia', 'Vietnam', 'Israel']]

You can access an item inside a list that is itself inside another list by chaining two sets of square brackets together. For example, in the above list variable asia you have three lists which represent a 3 × 3 matrix. If you want to display the items of the first list then specify the list variable followed by the index of the list which you need to access within the brackets, like asia[0]. If you want to access “Japan” item inside the list then you need to specify the index of the list within the list and followed by the index of the item in the list, like asia[0][1]. You can even modify the contents of the list within the list. For example, to replace “Thailand” with “Philippines” use the code in.

Shelton Coutinho
Shelton Coutinho
Articles: 13

Leave a Reply

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