Lists in Python 3

by Alex
Lists

A list is a very convenient data structure that can store different types of data. It can also be called a data sequence. Unlike dictionaries, lists have an index order. This means that each item in a list has an index, which will not change unless it is manually changed. In the case of other structures, such as dictionaries, this may be different. For example, dictionaries have no indexes for their keys, so you can’t just point to the second or third element, because there is no such order. This data structure should be thought of as a bag of jumbled things with no particular order. Indexing: it is important to note that list indexing starts at 0 (zero). This means that the first element in the list is actually zero in the Python world. This is very important to keep in mind.

Variability: lists are a modifiable type, which means that you can add or remove elements from them. Let’s look at some examples. Where is it used? Lists are a common data structure in Python. They are used for a variety of purposes. MethodActivity.append()method to add items to a list.insert()method to add items to a specific location in a list.index()to get the item index.clear()to clear the list.remove()to remove a list item.reverse()to reverse the list.count()to count the number of items in the listsum()to add list itemsmin()shows the item with the lowest value in the listmax()item with the highest value in the list

Tips for working with lists

  1. Lists are created using square brackets [].
  2. Elements of the list must be separated by commas.
  3. Syntax rules specific to certain data types must be observed within a list. For example, if a string must have quotation marks, they must be used inside the list, but they must not be used for numbers and boolean values.

Next is a list with values of different types. This is an excellent example, demonstrating the nuances of lists. Let’s see.

>>> p_datatypes = ["Python", "orange", 23, 51, False, "False", "22"]
>>> print(p_datatypes)
"Python", "orange", 23, 51, False, "False", "22"
  1. First of all, you can see that there are values of different types inside. They are a string, an integer, a boolean value, and a string again.
  2. The last two items in the list are strings, although they may resemble a boolean type and an integer. However, the use of quotation marks explicitly indicates that they are strings in Python.
  3. Finally, if you look at the indexes of the items, you can see that the zero item is “Python” and the sixth item is “22”. Both are strings. Although there are 7 elements, the last index is 6.

Access to items: The items in the list can be accessed using their index, indicated in square brackets. For example, to get the first element (“Python”) write as follows: p_datatypes[0]. To get element 23: p_datatypes[2]. Let’s look at the other examples. The last element of the following list is a False boolean value. We access it inside the print function.

>>> p_datatypes = ["Python", "orange", 23, False]
>>> print(p_datatypes[3])
False

And here is getting the first item from the list.

>>> p_datatypes = ["Python", "orange", 23, False]
>>> print(p_datatypes[0])
'Python'

Reverse indexing

  1. Reverse indexing. List items can also be called starting at the end – this is called reverse indexing. Unlike normal indexing, reverse indexing starts with -1, not 0. To get the last element of the list p_datatypes: p_datatypes[-1].
  2. Similarly, p_datatypes[-2] will return the second element from the end, and so on.

This approach has advantages in certain situations. It is much more practical and efficient to use reverse indexing, because thanks to it you can not count the number of elements in the list. Another advantage comes in the case of changing the length of the list. In this case, again, you don’t have to count items from the beginning to get to the final one.

>>> p_datatypes = ["Python", "orange", 23, False]
>>> print(p_datatypes[-1])
False

List methods and functions

Method #1: .append()

append() is probably the most used list method. It is used to add items to a list. Now let’s look at an example where the .append() method is used to add a new item to the end of the list.

>>> p_datatypes = ["Python", "orange"]
>>> p_datatypes.append("BMW")
>>> print(p_datatypes)
["Python", "orange", "BMW"]

Method #2: .insert()

.insert() is another useful method for lists. It is used to insert an item into a list by index. Let’s look at an example: .insert() takes two arguments: the index where the new item should be inserted, and the item itself.

>>> p_datatypes = ["Python", "orange"]
>>> p_datatypes.insert(1, "BMW")
>>> print(p_datatypes)
["Python", "BMW", "orange"]

Method #3 .index()

.index() helps to determine the index of an element. Next is an example of how to get the index of a particular element.

>>> lst = [1, 33, 5, 55, 1001]
>>> a = lst.index(55)
>>> print(a)
3

Method #4: .clear()

The .clear() method removes all items from the list.

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> lucky_numbers.clear()
>>> print(lucky_numbers)
[]

Method #5: .remove()

The .remove() method removes a specific item from the list.

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> lucky_numbers.remove(101)
>>> print(lucky_numbers)
[5, 55, 4, 3, 42]

Method #6: .reverse()

The .reverse() method reverses the order of elements in the list.

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> lucky_numbers.reverse()
>>> print(lucky_numbers)
[42, 101, 3, 4, 55, 5]

Method #7: .count()

The .count() method is used to count how often a particular item occurs in the list. In the following example, we count how often the number 5 occurs in the list. The result is 1, which means that number 5 occurs only once.

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(lucky_numbers.count(5))
1

In the same case, there is no 1 in the list, so the output will be 0.

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(lucky_numbers.count(1))

Function #8: sum()

The function sum() returns the total sum of all the numbers in the list.

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(sum(lucky_numbers))
210

Function #9: min()

The function min() will show the element with the minimum value in the list. Let’s look at an example.

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(min(lucky_numbers))
3

Function #10: max()

The max() function will show the item with the maximum value in the list. Example:

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(max(lucky_numbers))
101

Advanced tips Here are some more functions and methods of lists, the features of which we will discuss later:

  1. .sort()
  2. .find()
  3. .pop()
  4. .len() – used in other data structures.
  5. zip()
  6. map()
  7. filter()
  8. List Comprehension (a very practical and convenient way of working with lists)

How to shuffle list items

You can use the random library to shuffle the elements in a list. This is a standard Python library that offers various useful elements ( randrange and randint are among the most used). This library also has a shuffle method that can be used after random is imported: random.shuffle(list).

>>> import random
>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> random.shuffle(lst)
>>> print(lst)
[7,3,5,2,6,8,4,1,9]

Problems for the lesson

Try solving the problems for this lesson to consolidate knowledge. 1. Finish the code to display the last item in the list.

# this code
sample = ["abc", "xyz", "aba", 1221]
# required output:
# 1221

2. Fill in the code to output the expanded list.

# this code
sample = ["Green", "White", "Black"]
print(sample)
# required output:
# ["Red", "Green", "White", "Black", "Pink", "Yellow"]

3. Correct the errors in the code to calculate the sum of the elements in the list.

# this code
sample = ["11", "33", "50"]
print(sample.sum())
# required output:
# 94

A file with all the assignments: https://gitlab.com/PythonRu/python-dlya-nachinayushih/-/blob/master/lesson_6.py

List quiz

Take the quiz for this lesson to test your knowledge. The test has 5 questions, with an unlimited number of attempts. How do you create a list? l = [1, 2, 3] l = list(1, 2, 3) All variants are true l = list[1, 2, 3] Continue to What this code will output:

a = [ 1, 342, 223, 'India', 'Fedora']
print(a[-3])

Error 342 223 ‘India’ Continue to What will this code print out:

sample = [10, 20, 30]
sample.append(60)
sample.insert(3, 40)
print(sample)

[60, 10, 20, 30, 40] [10, 20, 30, 40, 60] [10, 20, 30, 60, 40] [10, 20, 30, 40] Continue How do I get the element with the maximum value in a number list? len(number_list) max(number_list) number_list.max() number_list.count() number_list.maximum() Continue to What this code will output:

lake = ["Python", 51, False, "22"]
lake.reverse()
lake.reverse()
print(lake[-2])

-2 51 False [51] Continue Continue Share your results via Facebook Twitter VK Repeat If you find a mistake, a typo, or know how to improve this lesson, email. It can be found at the bottom of the site.

Related Posts

LEAVE A COMMENT