Lists

1. The list is a type of data in Python used to store multiple objects. It is an ordered and mutable collection of comma-separated items between square brackets, e.g.:

 

2. Lists can be indexed and updated, e.g.:


 

3. Lists can be nested, e.g.:


 

4. List elements and lists can be deleted, e.g.:


 

5. Lists can be iterated through using the for loop, e.g.:


 

6. The len() function may be used to check the list’s length, e.g.:


 

7. A typical function invocation looks as follows: result = function(arg), while a typical method invocation looks like this:result = data.method(arg).

 

8. You can use the sort() method to sort elements of a list, e.g.:

  • Both sort() and sorted() sort a list in ascending order.
  • sort() is a method and sorted() is a built-in function.
  • sort() changes the list in place, while sorted() creates a new list
  • sort() is defined only for lists, while sorted() accepts any iterable (such as strings and tuples)

 

9. There is also a list method called reverse(), which you can use to reverse the list, e.g.:

or

In Python, the slice notation [::-1] returns the elements of a data collection, such as a list, in reverse order.

 

10. If you have a list list1, then the following assignment: list2 = list1 does not make a copy of the list1 list, but makes the variables list1 and list2 point to one and the same list in memory. For example:

 

11. If you want to copy a list or part of the list, you can do it by performing slicing:


 

12. You can use negative indices to perform slices, too. For example:


 

13. The start and end parameters are optional when performing a slice: list[start:end], e.g.:


 

14. You can delete slices using the del instruction:


 

15. You can test if some items exist in a list or not using the keywords in and not in, e.g.:

 

16. List comprehension allows you to create new lists from existing ones in a concise and elegant way. The syntax of a list comprehension looks as follows:


which is actually an equivalent of the following code:

Let’s assume that we’re able to use the selected numbers to represent any chess piece. We can also assume that every row on the chessboard is a list.

Look at the code below:

It builds a list containing eight elements representing the second row of the chessboard – the one filled with pawns (assume that WHITE_PAWN is a predefined symbol representing a white pawn).

The same effect may be achieved by means of a list comprehension, the special syntax used by Python in order to fill massive lists.

The part of the code placed inside the brackets specifies:

the data to be used to fill the list (WHITE_PAWN)
the clause specifying how many times the data occurs inside the list (for i in range(8))

Here’s an example of a list comprehension ‒ the code creates a five-element list filled with the first five natural numbers raised to the power of 3:


 

17. Swapping the lists’s elements.

you can easily swap the list’s elements to reverse their order:


Run the snippet. Its output should look like this:

[5, 3, 8, 1, 10]

Will it still be acceptable with a list containing 100 elements? No, it won’t. You use the for loop to do the same thing automatically, irrespective of the list’s length.


This is how we’ve done it:

 

 

Let us show you some other list comprehension examples:

Example #1:


The snippet produces a ten-element list filled with squares of ten integer numbers starting from zero (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)

Example #2:

The snippet creates an eight-element array containing the first eight powers of two (1, 2, 4, 8, 16, 32, 64, 128)

Example #3:


The snippet makes a list with only the odd elements of the squares list.

18. You can use nested lists in Python to create matrices (i.e., two-dimensional lists). For example:

Table - a two-dimensional array


 

18. You can nest as many lists in lists as you want, thereby creating n-dimensional lists, e.g., three-, four- or even sixty-four-dimensional arrays. For example:

Cube - a three-dimensional array


 

Exercise 1

What is the output of the following snippet?

 

Exercise 2

What is the output of the following snippet?

 

Exercise 3

What happens when you run the following snippet?

Exercise 4

What is the output of the following snippet?

 

Exercise 5

What is the output of the following snippet?

 

Exercise 6

What is the output of the following snippet?

 

Exercise 7

What is the output of the following snippet?

 

Exercise 8

What is the output of the following snippet?

 

Exercise 9

Insert in or not in instead of ??? so that the code outputs the expected result.

 

Exercise 10

What is the output of the following snippet?

 

['A', 'D', 'F', 'Z']

 

Exercise 11

What is the output of the following snippet?

 

[1, 2, 3]

 

Exercise 12

What is the output of the following snippet?

 

[' ', 'C', 'B', 'A']

 

Ex. 13

What is the output of the following code snippet?

 

{1: 'one', 2: 'two', 3: 'three'}

  • After line 3 of the code, d1 and d2 refer to the same dictionary. In other words, d1 and d2 are two variables that point to the same dictionary in memory and not two separate copies of it.
  • The instruction in line 4 removes the reference d1, but the variable d2 will continue to point to the starting dictionary. Therefore, in line 6, the print()function will print the entire dictionary.

 

Ex. 14

What is the output of the following code snippet?

 

4 3

  • The program executes the for loop 4 times, according to the four elements of the lst list. Due to the if condition, the program will execute the print statement only for the values 3 and 0 in the list.
  • In the print statement, n is used as an index to get the corresponding value in lst.
  • Due to the presence of the end=" " parameter the numbers are printed on a single line separated by a space.
  • Here’s how the for loop works:
    • First iteration: n = 3.
      The if condition is True because 3 is different from 2 and 4.
      The print statement outputs 4 to the screen:print(lst[3], end=" ") -> print(4, end=" ") -> 4.(The list index starts with 0).
    • Second iteration: n = 2.
      The if condition is False.
    • Third iteration: n = 3.
      The if condition is True because 0 is different from 2 and 4.
      The print statement outputs 3 to the screen:print(lst[0], end=" ") -> print(3, end=" ") -> 3.
    • Fourth iteration: n = 4.
      The if condition is False and the program ends.

 

Ex.15

What is the output of the following code snippet?

['a', 'b', 'C', 'Z', ' ']

[' ', 'a', 'b', 'C', 'Z']

[' ', 'C', 'Z', 'a', 'b']

['C', 'Z', 'a', 'b', ' ']

 

Ex. 16

What is the output of the following code snippet?

[1, 2, 3, 4, 5, ['a', 'b']]

[1, 2, 3, 4, 5, [6, 7]]

[1, 2, 3, 4, 5, [6, 7], 'a']

[1, 2, 3, 4, 5, 6, 7]

 

Ex.17

What is the output of the following code snippet?


 

Correct answer

7

 

Ex. 18

What is the output of the following code snippet?

[0, -1, -2]

A ValueError exception

[]

[-1, -2, -3]

 

Ex. 19

What is the output of the following code snippet?

[8, 7, 1, 5, 9]

[0, 8, 7, 1, 5, 9]

[3, 7, 1, 5, 9]

A SyntaxError exception

 

Ex. 20

What is the output of the following code snippet?


 

Correct answer

['?', '#', '&']

#

 

Scenario

Imagine a list – not very long, not very complicated, just a simple list containing some integer numbers. Some of these numbers may be repeated, and this is the clue. We don’t want any repetitions. We want them to be removed.

Your task is to write a program which removes all the number repetitions from the list. The goal is to have a list in which all the numbers appear not more than once.

Note: assume that the source list is hard-coded inside the code – you don’t have to enter it from the keyboard. Of course, you can improve the code and add a part that can carry out a conversation with the user and obtain all the data from her/him.

Hint: we encourage you to create a new list as a temporary work area – you don’t need to update the list in situ.