How to set up smartphones and PCs. Informational portal
  • home
  • News
  • Lists (list). List Functions and Methods

Lists (list). List Functions and Methods

Today I will talk about such a data type as lists, their operations and methods, list comprehensions, and the use of lists.

What are lists?

Lists in Python are ordered mutable collections of objects of arbitrary types (much like an array, but the types may differ).

To use lists, you need to create them. There are several ways to create a list. For example, you can process any iterable object (for example, ) with the built-in function list:

>>> list("list") ["list"]

A list can also be created using a literal:

>>> s = # Empty list >>> l = [ "s" , "p" , [ "isok" ], 2 ] >>> s >>> l ["s", "p", ["isok "], 2]

As you can see from the example, a list can contain any number of any objects (including nested lists), or it can contain nothing.

And another way to create a list is list generators. A list comprehension is a way to construct a new list by applying an expression to each element of a sequence. List comprehensions are very similar to a loop.

>>> c = [ c * 3 for c in "list" ] >>> c ["lll", "iii", "sss", "ttt"]

A more complex construction of the list generator is also possible:

>>> c = [ c * 3 for c in "list" if c != "i" ] >>> c ["lll", "sss", "ttt"] >>> c = [ c + d for c in "list" if c != "i" for d in "spam" if d != "a" ] >>> c ["ls", "lp", "lm", "ss", "sp", "sm", "ts", "tp", "tm"]

But in complex cases, it is better to use a regular for loop to generate lists.

List Functions and Methods

Create created, now you need to do something with the list. Basic and list methods are available for lists.

List methods table

MethodWhat is he doing
list.append(x)Adds an element to the end of the list
list.extend(L)Extends the list list by appending all elements of the list L to the end.
list.insert(i, x)Inserts the value x on the i-th element
list.remove(x)Removes the first element in the list that has the value x. ValueError if no such element exists
list.pop([i])Removes the i-th element and returns it. If no index is specified, the last element is removed.
list.index(x,])Returns the position of the first element with value x (searching from start to end)
list.count(x)Returns the number of elements with value x
list.sort() Sorts a list based on a feature
list.reverse() Expands the list
list.copy() Shallow copy of the list
list.clear() Clears the list

It should be noted that list methods, unlike , change the list itself, and therefore the result of the execution does not need to be written to this variable.

>>> l = [ 1 , 2 , 3 , 5 , 7 ] >>> l . sort() >>> l >>> l = l . sort() >>> print(l) None

And finally, examples of working with lists:

>>> a = [ 66.25 , 333 , 333 , 1 , 1234.5 ] >>> print (a . count (333 ), a . count (66.25 ), a . count ("x")) 2 1 0 >>> a. insert (2 , - 1 ) >>> a . append(333) >>> a >>> a . index (333 ) 1 >>> a . remove(333) >>> a >>> a . reverse() >>> a >>> a . sort() >>> a [-1, 1, 66.25, 333, 333, 1234.5]

Occasionally, to increase performance, lists are replaced with much less flexible ones.

To answer this question, I need to explain Unbounded Wildcards and Bounded Wildcards.
The content of this message has been compiled from the java documentation.

1. Unlimited wildcards

The boundless substitution type is specified using the wildcard character (?), for example, List. This is called a list of unknown type. There are two scenarios where an unrestricted wildcard is a useful approach:

    If you are writing a method that can be implemented using the functions provided in the Object.

    When code uses methods in a generic class that do not depend on a type parameter. For example, List.size or List.clear . Actually, Classso often used because most of the methods from Class do not depend on T .

2. Limited wildcards

Consider a simple drawing application that can draw shapes such as rectangles and circles. To represent these forms within the program, you can define a class hierarchy such as:

public abstract class Shape ( public abstract void draw(Canvas c); ) public class Circle extends Shape ( private int x, y, radius; public void draw(Canvas c) ( ... ) ) public class Rectangle extends Shape ( private int x, y, width, height; public void draw(Canvas c) ( ... ) )

These classes can be drawn on the canvas:

public class Canvas ( public void draw(Shape s) ( s.draw(this); ) )

Any drawing usually contains several shapes. Assuming they are presented as a list, it would be nice to have a method on the Canvas that draws them all:

public void drawAll(List shapes) ( for (Shape s: shapes) ( s.draw(this); ) )

Now the type rules say that drawAll() can only be called on lists exactly Shape: it cannot, for example, be called on a List . This is unfortunate since all the method does is read shapes from a list, so it can just as easily be called on a List . We really want the method to accept a list of any form: public void drawAll(list forms) ( ... ) Here is a small but very important difference: we have replaced the List type with on List. Now drawAll() will accept lists of any Shape subclass, so we can now call it if we want.

Listis an example of a restricted template. ? denotes an unknown type, however in this case we know that this unknown type is actually a subtype of Shape. (Note: this can be the shape itself or some subclass, it doesn't have to literally extend the shape.) We say that the Shape is upper bound wildcard.

Likewise, syntax? super T , which is a restricted wildcard, denotes an unknown type that is a supertype of T. A ArrayedHeap280, for example, includes ArrayedHeap280 , ArrayedHeap280 and ArrayedHeap280 . As you can see in the java documentation for the Integer class, Integer is a subclass of Number, which in turn is a subclass of Object.

One of the key features of Python that makes it so popular is its simplicity. Particularly captivating is the ease of working with various data structures - lists, tuples, dictionaries and sets. Today we will look at work with lists.

What is a list in Python?

List (list) is a data structure for storing objects of various types. If you have used other programming languages, then you should be familiar with the concept of an array. So, a list is very similar to an array, only, as mentioned above, it can store objects of various types. The size of the list is not static, it can be changed. A list, by its very nature, is a mutable data type. Read more about data types. A variable, defined as a list, contains a reference to a structure in memory, which in turn holds references to some other object or structure.

How are lists stored in memory?

As mentioned above, the list is a mutable data type. When it is created, an area is reserved in memory, which can be conditionally called some “container”, in which references to other data elements in memory are stored. Unlike such data types as number or string, the contents of the "container" of the list can be changed. In order to better visualize this process, take a look at the picture below. Initially, a list containing links to objects 1 and 2 was created, after the operation a = 3, the second link in the list now points to object 3.

Creating, modifying, deleting lists and working with its elements

You can create a list in one of the following ways.

> > > a => > > type(a)< class "list" >> > > b = list() > > > type(b)< class "list" >

You can also create a list with a predefined set of data.

> > > a => > > type(a)< class "list" >

If you already have a list and want to create a copy of it, you can use the following method:

> > > a = > > > b = a[:] > > > print (a) > > >

or do it like this:

> > > a = > > > b = list(a) > > > print(a) > > > print(b)

In case you perform a simple assignment of lists to each other, then the variable b will be assigned a reference to the same data element in memory that is referred to a, not a copy of the list a. Those. if you change the list a, then and b will also change.

> > > a = > > > b = a > > > print (a) > > > print (b) > > > a = 10 > > > print (a) > > > print (b)

Adding an element to the list is done using the append() method.

> > > a = > > > a.append(3 ) > > > a.append("hello" ) > > > print (a)

To remove an element from the list, if you know its value, use the remove(x) method, which will remove the first reference to that element.

> > > b => > > print (b) > > > b.remove(3 ) > > > print (b)

If you need to delete an element by its index, use the command del list_name[index].

> > > c = > > > print (c) > > > del c > > > print (c)

To change the value of a list element, knowing its index, you can directly access it.

> > > d = > > > print (d) > > > d = 17 > > > print (d)

You can clear the list simply by re-initializing it, as if you were re-creating it.To access an element of a list, specify the index of that element in square brackets.

> > > a = > > > a 7

You can use negative indexes, in which case the count will go from the end, for example, to access the last element of the list, you can use the following command:

> > > a[-1] 0

To get some sublist from a list at a specific index range, specify the start and end indexes in square brackets, separated by a colon.

> > > a

List Methods

list append(x)

Adds an element to the end of the list. The same operation can be done like this a = [x].

> > > a = > > > a.append(3 ) > > > print(a)

list.extend(L)

Extends an existing list by adding all the elements from the list L. Equivalent to command a = L.

> > > a => > > b => > > a.extend(b) > > > print(a)

list.insert(i, x)

Insert element x into position i. The first argument is the index of the element after which the element will be inserted. x.

> > > a = > > > a.insert(0 , 5 ) > > > print (a) > > > a.insert(len (a), 9 ) > > > print (a)

list.remove(x)

Removes the first occurrence of an element x from the list.

> > > a = > > > a.remove(1 ) > > > print(a)

list.pop([i])

Removes an element from a position i and returns it. If you use the method without an argument, then the last element from the list will be removed.

> > > a = > > > print (a.pop(2 )) 3 > > > print (a.pop()) 5 > > > print (a)

list.clear()

Removes all elements from the list. Equivalently del a[:].

> > > a => > > print(a) > > > a.clear() > > > print(a)

list.index(x[, start[, end]])

Returns the index of the element.

> > > a = > > > a.index(4 ) 3

list.count(x)

Returns the number of occurrences of an element x to the list.

> > > a= > > > print (a.count(2 )) 2

list.sort(key=None, reverse=False)

Sorts the elements in the list in ascending order. To sort in reverse order, use the flag reverse=True. Additional features opens parameter key, see the documentation for more information.

> > > a => > > a.sort() > > > print(a)

list.reverse()

Reverses the order of elements in a list.

> > > a = > > > a.reverse() > > > print(a)

list.copy()

Returns a copy of the list. Equivalently a[:].

> > > a = > > > b = a.copy() > > > print (a) > > > print (b) > > > b = 8 > > > print (a) > > > print (b)

List Comprehensions

List Comprehensions most often translated into Russian as a list abstraction or list inclusion, is part of the language syntax, which provides an easy way to build lists.Easiest job list comprehensions show with an example. Let's say you need to create a list of integers from 0 before n, where n pre-set. The classic way to solve this problem would look like this:

N = int (input ()) a = for i in range (n): a.append(i) print (a)

Usage list comprehensions makes it much easier:

N = int(input()) a = print(a)

or even like this, in case you don't need to use n:

A = print(a)

P.S.

If you are interested in the topic of data analysis, then we recommend that you familiarize yourself with the library pandas. On our website you can find All lessons in the library pandas collected in a book

Top Related Articles