Examples of working with Python lists

by Alex
Examples of working with Python lists

A Python list is a sequence of values of any type: string, number, floating point number or even mixed type. This material will talk about the functions of lists, how to create them, add elements, represent them in reverse order, and many others.

Create Python lists

To create a Python list, you need to enclose elements in square brackets:

my_list = [1, 2, 3, 4, 5]

A list might look like this:

my_list = ['one', 'two', ' three', 'four', 'five']

You can mix and match content types:

my_list = ['one', 10, 2.25, [5, 15], 'five']

Nested lists as in the example above are supported. Any list item can be accessed through its index. Python uses an indexing system starting from zero.

third_elem = my_list[2]

The principle is similar to strings.

Changing a list

Lists are modifiable objects, so their elements can change, or their order can be changed. If there is such a list:

my_list = ['one', 'two', ' three', 'four', 'five']

Then its third element can be changed as follows:

my_list[2] = ' zero'

If you display it now, it will look like this:

['one', 'two', 'zero', 'four', 'five']

If the index is a negative number, it will be counted from the last element.

my_list = ['one', 'two', ' three', 'four', 'five']
elem = my_list[-1]
print(elem)

The output of this code is ‘five’.

Passage (iteration) through the list

You can read the elements of a list using the following loop:

my_list = ['one', 'two', ' three', 'four', 'five']
for elem in my_list:
   print(elem)

This is how you can read the elements of a list. As for updating them:

my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list))
    my_list[i]+=5
   print(my_list)

The result will be as follows:

[6, 7, 8, 9, 10]

The len() function is used to return the number of elements, and range() is used to return the list of indexes. It is worth remembering that a nested list is always a single item, no matter how many items it contains.

my_list = ['one', 10, 2.25, [5, 15], 'five']
print(len(my_list))

The result of the code above is 5.

A list slice

You can get a slice of a list with the help of the operator (:):

my_list = ['one', 'two', ' three', 'four', 'five']
print(my_list[1:3])

The code result above is ['two', 'three'] If the first number is removed, the slice will start with the first element, and if the second number is removed, the slice will start with the last element. If you remove the numbers and leave only a colon, the whole list will be copied.

my_list = ['one', 'two', ' three', 'four', 'five']
print(my_list[1:3])
print(my_list[1:])
print(my_list[:3])
print(my_list[:])

This year’s result:

['two', 'three']
['two', 'three', 'four', 'five']
['one', 'two', 'three']
['one', 'two', 'three', 'four', 'five']

Since lists are modifiable, you can change items using the slice operator:

my_list = ['one', 'two', ' three', 'four', 'five']
my_list[1:3] = ['Hi', ' Peace']
print(my_list)

Result:

['one', 'Hi', 'Peace', 'four', 'five']

Insert into a list

The insert method can be used to insert an item into a list:

my_list = [1, 2, 3, 4, 5]
my_list.insert(1,'Hi')
print(my_list)

Result:

[1, 'Hi', 2, 3, 4, 5]

The indices for the inserted elements also start with zero.

Add to list

The append method can be used to add an item to the list:

my_list = ['one', 'two', 'three', 'four', 'five']
my_list.append('one more')
print(my_list)

Result:

['one', 'two', 'three', 'four', 'five', 'one more']

You can add more than one item this way:

my_list = ['one', 'two', ' three', ' four', 'five']
list_2 = ['six', ' seven']
my_list.extend(list_2)
print(my_list)

Result:

['one', 'two', 'three', 'four', 'five', 'six', 'seven']

This will not change list_2.

Sort list

The sort method must be used to sort the list.

my_list = ['cde', 'fgh', 'abc', 'klm', 'opq']
list_2 = [3, 5, 2, 4, 1]
my_list.sort()
list_2.sort()
print(my_list)
print(list_2)

Output:

['abc', 'cde', 'fgh', 'klm', 'opq']
[1, 2, 3, 4, 5]

Reverse the list

You can reverse the order of the items in the list using the reverse method:

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)

Result:

[5, 4, 3, 2, 1]

Item index

The index method can be used to get the index of an element:

my_list = ['one', 'two', 'three', 'four', 'five']
print(my_list.index('two'))

Result 1. If there is more than one such element in the list, the function will return the index of the first one.

Delete item

You can delete an item by writing its index in the pop method:

my_list = ['one', 'two', ' three', 'four', 'five']
removed = my_list.pop(2)
print(my_list)
print(removed)

Result:

['one', 'two', 'four', 'five']
three

If you do not specify an index, the function will delete the last element.

my_list = ['one', 'two', ' three', 'four', 'five']
removed = my_list.pop()
print(my_list)
print(removed)

Result:

['one', 'two', 'three', 'four']
five

The element can be removed using the remove method.

my_list = ['one', 'two', ' three', 'four', 'five']
my_list.remove('two')
print(my_list)

Result:

['one', 'three', 'four', 'five']

The del operator can be used for the same purpose:

my_list = ['one', 'two', ' three', 'four', 'five']
del my_list[2]
print(my_list)

Result:

['one', 'two', 'four', 'five']

You can remove multiple elements with the slice operator:

my_list = ['one', 'two', ' three', 'four', 'five']
del my_list[1:3]
print(my_list)

Result:

['one', 'four', 'five']

Aggregation Functions

Python has some aggregation functions:

my_list = [5, 3, 2, 4, 1]
print(len(my_list))
print(min(my_list))
print(max(my_list))
print(sum(my_list))

sum() works only with numeric values. And max(), len() and others can be used with strings as well.

Compare Lists

In Python 2, you can compare the elements of two lists using the cmp function:

my_list = ['one', 'two', 'three', 'four', 'five']
list_2 = ['three', 'one', 'five', 'two', 'four']
print(cmp(my_list,list_2))

It will return -1 if the lists don’t match, and 1 otherwise. Python 3 uses the(==) operator to do this:

my_list = ['one', 'two', 'three', 'four', 'five']
list_2 = ['three', 'one', 'five', 'two', 'four']
if (my_list == list_2):
   print('match')
else:
   print('don't match')

The result do not match.

Mathematical operations on lists:

You can use the(+) operator to combine lists:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
print(list_1 + list_2)

Result:

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

The list can be repeated using the multiplication operator:

list_1 = [1, 2, 3]
print(list_1 * 2)

Result:

[1, 2, 3, 1, 2, 3]

Lists and strings

To convert a string into a character set, you can use the list function:

my_str = ' Monty Python'
my_list = list(my_str)
print(my_list)

Result:

['M', 'o', 'n', 't', 'y', ' ', 'P', 'y', 't', 'h', 'o', 'n']

The list function is used to break down a string into individual characters. You can use the split method to split a string into words:

my_str = 'Monty Python'
my_list = my_str.split()
print(my_list)

Result:

['Monty', 'Python']

It returns a regular list, where each word can be interacted with via an index. The split character can be any character, not just a space.

my_str = ' Monty-Python'
my_list = my_str.split('-')
print(my_list)

The result will be similar:

['Monty', 'Python']

Combine a list into a string

The reverse process is combining list items into a string. This is done using the join method:

my_list = ['Monty', 'Python']
delimiter = ' '
output = delimiter.join(my_list)
print(output)

Monty Python result.

Aliasing (aliasing)

When two variables refer to the same object:

my_list = ['Monty', 'Python']
list_2 = my_list

Aliasing means that the object is referenced by more than one name. The following example shows how variable lists are aliased:

my_list = ['Monty', 'Python']
list_2 = my_list
list_2[1] = 'Java:)'
print(my_list)

Result:

['Monty', 'Java:)']

List_2 has changed, but since it refers to the same object, the original list has also changed. Using “aliases” when working with lists is not recommended. In general, working with lists in Python is very easy.

Related Posts

LEAVE A COMMENT