List – Python

What are lists?

List (array) is a data structure consisting of collection of elements. Each element has a value and an index. Indexes in lists start from 0. Lists in python can contain values of different types (e.g. strings, integers, objects, etc.). As an example of how indexing works we have a String (an array of characters) “Monty Python”, which is displayed in figure below [ Source ].

vikad

Usually accessing elements of array is done by having the variable name and brackets with an index of the desired element (e.g. variable[2]). Unlike most other programming languages in Python it is possible to access arrays with negative numbers – this will access the elements from the end of the array.

Examples

Declaring and initializing lists

integer_list = [1, 22, 333, 4444, 32, 21, 5]
string_list = ["hello", "iax0583", "course"]
list_list = [[1, 2], [3, 4], [5, 6], [7, 8]]
mixed_list = [1, "hello", [4, 24], {"key": 2}]

Accessing values

# element at index 1
print(mixed_list[1]) # "hello"
# elements from index 1 to 3 (3 not included)
print(integer_list[1:3]) # [22, 333]
# 2 elements from the end
print(string_list[-3:-1]) # ["iax0583", "course"]
# 3 elements from the end, reversed order
print(integer_list[-1:-4:-1]) # [5, 21, 32]

Above code produces following output:

hello
[22, 333]
['hello', 'iax0583']
[5, 21, 32]

 

Iterating over elements

# Iterate over each string_list element
for index in range(len(string_list)):
    print(string_list[index])

# Iterate over each mixed_list element using iterators
for element in mixed_list:
    print(element)
hello
iax0583
course
1
hello
[4, 24]
{'key': 2}

List Operations

print(len(list_list)) # Length of the list
print(sum(integer_list)) # Add all list elements
print(string_list + integer_list) # Concatenate two lists
print(string_list * 2) # Repeat list
print(333 in integer_list) # Check if element exists in list
4
4858
['hello', 'iax0583', 'course', 1, 22, 333, 4444, 32, 21, 5]
['hello', 'iax0583', 'course', 'hello', 'iax0583', 'course']
True

List Modification

print(integer_list) # Original list
integer_list[1] = 555 # 22 -> 555
print(integer_list)
del integer_list[1] # 555 no longer exists
print(integer_list)
integer_list = [1, 22, 333, 4444, 32, 21, 5] # Restore default values
print(integer_list)
[1, 22, 333, 4444, 32, 21, 5]
[1, 555, 333, 4444, 32, 21, 5]
[1, 333, 4444, 32, 21, 5]
[1, 22, 333, 4444, 32, 21, 5]

List Methods

append

Add a new element at the end of the list.

print(integer_list)
integer_list.append(123) # Add at the end
print(integer_list)
[1, 22, 333, 4444, 32, 21, 5]
[1, 22, 333, 4444, 32, 21, 5, 123]

extend

Add several elements at the end of the list (takes iterable e.g. list or dictionary as a parameter).

print(integer_list)
integer_list.extend(integer_list) # Extend list with a list
print(integer_list)
[1, 22, 333, 4444, 32, 21, 5, 123]
[1, 22, 333, 4444, 32, 21, 5, 123, 1, 22, 333, 4444, 32, 21, 5, 123]

insert

Insert element at a specific index.

print(integer_list)
integer_list.insert(1, 1337) # Add at index 1
print(integer_list)
[1, 22, 333, 4444, 32, 21, 5, 123, 1, 22, 333, 4444, 32, 21, 5, 123]
[1, 1337, 22, 333, 4444, 32, 21, 5, 123, 1, 22, 333, 4444, 32, 21, 5, 123]

remove

Remove particular element from the list (note that it only removes first occurrence).

print(integer_list)
integer_list.remove(21) # Remove item with value 21
print(integer_list)
[1, 1337, 22, 333, 4444, 32, 21, 5, 123, 1, 22, 333, 4444, 32, 21, 5, 123]
[1, 1337, 22, 333, 4444, 32, 5, 123, 1, 22, 333, 4444, 32, 21, 5, 123]

pop

Pop value from certain index, without parameter pop from the end of the list.

print(integer_list)
integer_list.pop(1) # Remove element at index 1
integer_list.pop() # Remove last value
print(integer_list)
[1, 1337, 22, 333, 4444, 32, 5, 123, 1, 22, 333, 4444, 32, 21, 5, 123]
[1, 22, 333, 4444, 32, 5, 123, 1, 22, 333, 4444, 32, 21, 5]

count

Count how many times an element appears in the list.

print(integer_list)
print(integer_list.count(333)) # count 333's
[1, 22, 333, 4444, 32, 5, 123, 1, 22, 333, 4444, 32, 21, 5]
2

sort

Sort list in ascending order unless ‘reverse=True’ is passed as an argument.

print(integer_list)
integer_list.sort()
print(integer_list)
integer_list.sort(reverse=True) # Reverse order to the list
print(integer_list)
[1, 22, 333, 4444, 32, 5, 123, 1, 22, 333, 4444, 32, 21, 5]
[1, 1, 5, 5, 21, 22, 22, 32, 32, 123, 333, 333, 4444, 4444]

Note that when sorting string lists, uppercase letters have ‘lower’ value than lowercase letters. To understand why this is, refer to ASCII table.

reverse

Reverse the list order.

print(integer_list)
integer_list.reverse() # Print list in reverse order
print(integer_list)
[1, 1, 5, 5, 21, 22, 22, 32, 32, 123, 333, 333, 4444, 4444]
[4444, 4444, 333, 333, 123, 32, 32, 22, 22, 21, 5, 5, 1, 1]

copy

Create a copy of the list.

print(integer_list)
new_list = integer_list.copy() # Make a copy of the list
print(new_list)
[1, 1, 5, 5, 21, 22, 22, 32, 32, 123, 333, 333, 4444, 4444]
[1, 1, 5, 5, 21, 22, 22, 32, 32, 123, 333, 333, 4444, 4444]

Note that creating a new variable and assigning existing list as its value will create a reference not copy! This means that when one modifies the values of one list, the other lists values change as well – the values are in the same memory area.

Advanced Techniques

List comprehension

Concise way to procedually create lists. Syntax for this is

variable = [element_in_new_list for x in iterable]

In the element_in_new_list part, it is possible to create some operations with x which has new value in each iteration.

powers_list = [2 ** x for x in range(10)]
print(powers_list)

twos = [2 for x in range(10)]
print(twos)
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

Applications

List is a collection of elements. Usually the elements are of the same type, however it is possible to mix them. When some sort of similar data is collected it is reasonable to use lists as a datatype to store them in. Lists can be unordered or sorted.

Some example use cases for lists are:

  • Temperature measurements
  • Bingo Lotto numbers
  • Power consumption in each hour of the day
  • Grades for a course
  • Text (list of words)
  • Keyword cloud (for categorizing topics)

Exercises

Beginner

  1. String list
    1. Create a loop which runs 5 times
    2. Insert elements into a new list
    3. Display new list on screen
  2. Sort list
    1. Create a numeric list with at least 10 elements
    2. Sort the array in ascending order
    3. Display the sorted list
    4. Display last 3 elements of the list

Intermediate

  1. Nested Lists
    1. Ask for list length N
      1. Create list with N empty lists
      2. Ask for M (elements to be in in empty lists)
      3. For each empty list ask for M numbers
    2. Display List
    3. Sort all the nested lists
      1. Where list with even index is sorted in ascending order
      2. Where list with odd index is sorted in descending order
    4. Display all the nested lists

Advanced

  1. List comprehension
    1. Enter a sentence and save it as a variable
    2. Using list comprehension create a list which:
      1. Contains all the words as separate elements
      2. All the elements are capitalized

Further reading

  • Tutorialspoint Python 3 Lists [ Link ]
  • Python Docs – Lists [ Link ]
  • Wikipedia – Array [ Link ]
  • List comprehension [ Link ]

One thought on “List – Python

Leave a Reply

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