Python lists

by Alex
Python lists

In Python, a list is an ordered data structure used to store objects of arbitrary types. Unlike arrays, which contain only elements of the same type, lists are not bound to a particular kind of data, and have no hard limitations related to their size. With all of these features, lists are a fairly flexible tool for working with data in Python.

Creating and Filling

Before you can use a list, you need to initialize it. This can usually be done in several ways. This example shows what happens if you define an empty list called data and then display its contents.

>>> data = []
>>> data
[]

You can put all the necessary elements into the new list right at the moment of its creation, just by listing them in square brackets.

>>> data = [5, 'a', ['python'], 20]
>>> data
[5, 'a', ['python'], 20]

You can use different literals to fill lists, for example strings, by calling the built-in list function, as shown in the following example.

>>> data = list('python')
>>> data
['p', 'y', 't', 'h', 'o', 'n']

To automate the filling of aggregates of different types of objects, it is recommended to use list generators. These mechanisms allow you to apply a certain expression to each element of a given sequence.

Adding an item

When you add new data to a list its size is automatically increased by the necessary number of cells. To add an item to the list in Python, use the append method, passing an object to be added as argument. This function will append the item to the end.

>>> data = list('pytho')
>>> data.append('n')
>>> data
['p', 'y', 't', 'h', 'o', 'n']

If necessary, any of the objects can be placed by the given index in the list. A method named insert is used for this purpose. Calling it for the existing list, you need to pass the desired number of the element and the object itself as arguments.

>>> data = list('ython')
>>> data.insert(0, 'p')
>>> data
['p', 'y', 't', 'h', 'o', 'n']

It’s worth taking into account that the numbering of objects in the list is done from zero.

Extension of the list

If you need to merge two different data sets, represented in the form of lists, you should use the extend method. If you call it for one of the objects and take the other as an argument, they will be merged into a single whole.

>>> data1 = list('pyt')
>>> data2 = list('hon')
>>> data1.extend(data2)
>>> data1
['p', 'y', 't', 'h', 'o', 'n']

In this way, the elements of the second list will automatically be written to the end of the first list.

Deleting an item

The built-in functions of the platform allow you not only to add new data, but also to selectively get rid of it. To remove an item from a Python list, there are the remove and pop functions. In the case of the first method, the first indexed object with the selected value is deleted.

>>> data = list('pytthon')
>>> data.remove('t')
>>> data
['p', 'y', 't', 'h', 'o', 'n']

The pop method acts slightly differently, giving you the ability to extract a list item by any index, as shown in the following example.

>>> data = list('pytthonn')
>>> data.pop(3)
't'
>>> data.pop()
'n'
>>> data
['p', 'y', 't', 'h', 'o', 'n']

If you don’t pass the number of the required object, the last object in the list is deleted.

Cleaning of the list

The clear function can quickly remove all items from the list. For this purpose you need to call it through the object created before, as in the following example.

>>> data = list('python')
>>> data.clear()
>>> data
[]

It is worth noting that the list itself is not deleted after performing this operation.

Getting the size

Using the built-in method with the name len you can determine the number of elements in the Python list – its length. The function returns the total number of elements.

>>> data = list('python')
>>> len(data)
6

It is also possible to find out the number of selected objects with the count method. It has to be called for the current list. The item being searched for should be the arguments here.

>>> data = list('python')
>>> data.count('p')
1

With this function you can search not only for literals, but also for links to objects.

Sorting

The Python list is sorted using sort. The function sort arranges the items present in the selected list, automatically determining the most appropriate sorting method.

>>> data = list('python')
>>> data.sort()
>>> data
['h', 'n', 'o', 'p', 't', 'y']

For example, you can use this method to quickly change the current location of numbers, characters, or strings by sorting them in ascending or alphabetical order.

Flipping

As practice shows, sometimes there is a need to reverse the order of list items, for example, after the usual sorting. The method named reverse, which should be called for the list, will help to execute such task.

>>> data = list('python')
>>> data.reverse()
>>> data
['n', 'o', 'h', 't', 'y', 'p']

As you can see, this function simply reverses the order of the elements.

Copying

The usual assignment operation is not enough to get two identical lists, because in that case the object is not copied, but just another reference to it is created. The copy function will help you to get a full-fledged duplicate of the selected list.

>>> data1 = list('python')
>>> data2 = data1.copy()
>>> data2
['p', 'y', 't', 'h', 'o', 'n']

After calling this method on any existing list, an object similar in internal content is automatically created, which can then be freely assigned to another reference.

Search

To search a list in Python and find the index of a known item, resort to the index function. The argument of this method is the object or literal you’re looking for.

>>> data = list('python')
>>> data.index('o')
4

As you can see from the results of this action, the item index is displayed.

Converting a list into a string

A list consisting of characters can be converted to a string representation. To do this you have to concatenate a new string with the return value of the join function. The argument for this method should be a list. Here is an example of a conversion to a Python list string.

>>> data = list('python')
>>> str = ''.join(data)
>>> str
'python'

A string created this way gets the value of all the items in the list.

Getting a two-dimensional list

The basic capabilities of the platform allow you to work with the two-dimensional representation of a set of certain values in a program. You can implement this with a normal assignment operator by simply adding a list to a Python list to get a two-dimensional list.

>>> data = [[1, 2, 8], [2, 5, 6]]
>>> a[0]
[1, 2, 8]
>>> a[1]
[2, 5, 6]

Thus, we can see that a two-dimensional list is built on several one-dimensional ones.

Converting a dictionary into a list

As you know, the dictionary can store a given collection of arbitrary objects, accessed by a key. Using the items method, you can transform a dictionary into a list, as shown in the following example.

>>> dic = {}
>>> dic['name'] = 'John'
>>> dic['age'] = 25
>>> data = dic.items()
>>> data
dict_items([('name', 'John'), ('age', 25)])

The elements in the list initialized in this way are represented as pairs with a key and its corresponding value.

Conclusion

The standard Python library contains many useful functions for manipulating lists, allowing programmers to manipulate an ordered data set of different types effectively. Python 3 methods and operations with lists provide the ability not only to automatically change the internal content of any list, but also to convert it into other forms of information representation.

Related Posts

LEAVE A COMMENT