List in Python: functions and applicability

list python

The Python list stores data and objects in different ways and offers a linearly organized data structure, where each piece of data has a function and is accessed through an index.

Thus, this type of list is considered as a common structure, but with additions and specific functions.

There are two reasons to work with it: Python is a frequently used language and considered one of the simplest for beginners; moreover, the use of lists is common in any type of software development, making it necessary to know all the possibilities.

In this article, you will find information about creating lists in Python and other possible applications.

How to create a Python list?

Sort a collection of values ​​and separate them with a comma, enclosed in square brackets []. See examples below.

Example of empty list:

empty_list = []
print(empty_list)  # Output: []

Adding elements:

The Python list contains various elements such as numbers, names or other lists. There is more than one way to add elements to lists, we will show below:

by index in list

fruits = []
fruits[0]="aplle"
fruits[1]="banana"

In this way, you can arrange each element in a position chosen by you and later call them.

print(fruits)
['apple', 'banana']

In this list, apple occupies position 0 (first position), and banana occupies second position (1). This happens because, for computers, it is necessary to consider 0 as the first position, which does not happen in mathematics.

Methodlista.append

list = ['apple', 'banana', 'orange']
list.append('strawberry')
print(list)  # Saída: ['apple', 'banana', 'orange', 'strawberry']

In the method append, each added element passes to the end of the list.

Accessing list elements python

Access the elements of a list using the index, which starts at 0 for the first element.

number = [1, 2, 3, 4, 5]
print(number[0])  # Output: 1 (first element)
print(number[2])  # Output: 3 (third element)
print(number[-1])  # Output: 5 (last element)

In the first example, we selected the element in the first position. In the third example, [-1]it refers to the last element in the list.

Modifying list elements

number = [1, 2, 3, 4, 5]
number[2] = 10
print(number)  # Output: [1, 2, 10, 4, 5]

In the example, we change the number in the third position to 10.

operations with list python

There are several simple methods that organize, multiply or divide the lists. Follow:

Concatenation in list

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list_concatenated = list1 + list2
print(list_concatenated)  # output: [1, 2, 3, 4, 5, 6]

Elements, such as separate lists that need to be unified, are embedded.

Repetition in list

repeat_list = list1 * 3
print(repeat_list)  # output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

Repeats items in a list and can be done multiple times.

Verification in list

if 2 in list1:
    print("2 it's in list1")  # output: 2 it's in list1

It is a self-explanatory operation. In the example, we check if the value 2 is in the list.

Values: minimums, maximums and sum

# min(my_list)
# max(my_list)

my_list = [1, 2, 3]
min(my_list)
1
max(my_list)
3

This method serves to delimit the values ​​in the list, its usability depends on the application in which it is inserted.

scroll list python

# for item in list:
#     print(item)

my_list = [1, 2, 3]
for i in my_list:
    print(i)
>>> 1
>>> 2
>>> 3

this method

Python list methods: removing and sorting

To remove elements from a list, two methods can be used: 'pop()'and 'remove()'.

‘pop()’

list = [1, 2, 3, 4, 5]
element_removed = list.pop(2)
print(element_removed)  # output: 3
print(list)  # output: [1, 2, 4, 5]

last_element = list.pop()
print(last_element)  # Output: 5
print(list)  # Output: [1, 2, 4]

Removes element from a list based on its index and returns the removed value. However, if there is no index specification, by default the last element of the list is removed. The method pop()can be used to remove elements from an empty list, resulting in an error IndexError.

‘remove()’

list = [1, 2, 3, 2, 4, 5]
list.remove(2)
print(list)  # Output: [1, 3, 2, 4, 5]

list.remove(10)  # This will result in ValueError

Removes the first occurrence of a given value from the list. Still, unlike pop()remove()does not use an index to specify which element to remove, but rather the value of the element to be removed. Therefore, if the value is not present in the list, it will result in an error ValueError.

The first returns the removed element, allowing you to store it in a variable if needed. However, the second does not return the removed element, it just removes it from the list.

Inserting multiple items in the list

On the other hand, another way to create an empty list is by the while + input. The first one ( while) deals with a repetition loop, that is, a code structure that repeats a task some number of times.

For example:

while activity:
   activity= input(enter an activity: ')
   tasks.append(atividade)
enter an activity: Like the post
enter an activity: Share with social networks
enter an activity: Read other Homehost articles
enter an activity

Using the structure forto loop through the elements:

for task in tasks:
   print(tasks)
Like post about list in Python
Share with social networks
Read other Homehost articles

This ensures one print of all elements and can display them visually.

Python list applicability

This type of list can be used for any type of application, be it simple or complex. Thus, Python ends up being one of the most used languages ​​in different applications, usually focused on data analysis. As well as every programming language, it also works best in specific fields. See below for examples.

1. Storage and manipulation of data collections

Ideal for storing and organizing collections of data, such as a list of numbers, names, information records, among others, so they allow you to access, add, remove and modify elements in an efficient way.

2. Iteration and element processing

They make it easier to iterate through your elements using loops, such as for, allowing you to perform operations on each element, so they are especially useful when dealing with large datasets.

3. Implementing stacks and queues

Lists can be used to implement stacks ( stacks) along with queues ( queues), which are important data structures in algorithms and programs. For example: by adding elements to the end of the list and removing them from the end using the method pop(), you can create a stack. To create a queue, you can add elements to the end as well as remove them from the beginning using the pop(0).

4. Sorting and sorting data

They have built-in methods that make it easy to sort their elements. For example, the method sort()lets you sort the list in ascending order.

As such, it is useful when you need to sort data in a certain order.

5. Manipulation of structured data

Lists can contain other types of data such as dictionaries or even other lists, so this allows you to create complex data structures such as arrays (lists of lists) or lists of dictionaries. These structures are useful for representing structured data.

6. Implementation of advanced algorithms and data structures

Lists play a key role in implementing more advanced algorithms and data structures such as trees, graphs, and priority queues. The elements of these structures can be stored and manipulated using lists as a basis.

multidimensional lists

Earlier, we mentioned the multidimensional list concept when talking about lists within lists. These lists have multiple columns and rows, where data intersects with specific goals.

Multidimensional lists are widely applied in many cases, especially when looking to organize strategies, items, functions, data and the like.

It is common to observe the use of multidimensional lists in games and management systems, as demonstrated in the examples below.

Applicability of multidimensional list python

  1. Hangman: use a multidimensional matrix to store the word to be guessed and the current state of the revealed and hidden letters;
  2. Inventory Management System: store product information in a list of lists, as well as name, price and quantity in stock;
  3. Task Management System: use a multidimensional list to store tasks, where each task is a list containing title, description, deadline, status, etc;
  4. Agenda application: save appointments in a list of lists, where each appointment is a list with information such as date, time, description, location, etc;
  5. Hotel Reservation System: represent hotel rooms in a multidimensional array, where each cell contains occupancy and guest information;
  6. Image Processing: store the pixel values ​​of an image in a two-dimensional matrix to allow manipulations such as filtering, resizing, rotation, etc;
  7. Environment Simulation: use a three-dimensional matrix to represent a 3D environment, where each cell contains information about the objects present in that position;
  8. Movie Recommendation System: Keep movie information in a list of movies including title, genre, director, cast, user ratings, etc.

code version

array of integers

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

We have a 3×3 matrix represented by a list of three lists. You can access individual array elements using double indexes, such matriz[0][1]as accessing the value 2.

Multidimensional arrays are useful in many fields, such as image processing, computer graphics, physical simulations, games, among others. They allow representing data in the form of grids or tables, facilitating mathematical operations and manipulation of structured data.

List python of students and their grades

students = [["João", 8, 7, 6],
           ["Maria", 9, 9, 8],
           ["Pedro", 6, 7, 7]]

Above, each sublist represents a student, where the first element is the name and the following elements are grades in different subjects. You can access specific information for a student, for example, alunos[1][2]it would return Maria’s grade in the second subject (9).

You can use this multidimensional list structure to store tabular data such as student records, employee information as well as survey results, etc. It facilitates the organization and manipulation of related information.

game board

board     = [["X", "O", " "],
             [" ", "X", "O"],
             ["O", " ", "X"]]

Here, we have a tic-tac-toe board represented by a 3×3 matrix. Each cell contains an “X”, “O” symbol or empty space. You can access and modify elements to update the game state.

The use of multidimensional lists for this purpose allows checking the game rules, applying strategies and interacting with players .

Other Python list methods

Method extend: extends the list, adding the elements of the iterable argument, passed as a parameter. Example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # Output: [1, 2, 3, 4, 5, 6]

Method index: Returns the zero-based index of the first item in the list that has a value of x. If the value does not exist, the method throws an exception ValueError. Example:

fruits = ['apple', 'banana', 'orange', 'apple']
index = fruits.index('orange')
print(index)  # Output: 2

Method count: returns the number of times an element appears in the list. Example:

number = [1, 2, 3, 4, 4, 5, 4]
occurrences = number.count(4)
print(occurrences)  # Output: 3

Method sort: sorts the items in the list. Example:

number = [5, 2, 8, 1, 3]
number.sort()
print(number)  # Output: [1, 2, 3, 5, 8]

Method reverse: Reverses the order of the elements. Example:

number= [1, 2, 3, 4, 5]
number.reverse()
print(number)  # Output: [5, 4, 3, 2, 1]

Methodcopy: returns a shallow copy of the list. Example:

list1 = [1, 2, 3]
list2 = lista1.copy()
print(list2)  # Output: [1, 2, 3]

Method clear: Removes all existing items from the list. Example:

list = [1, 2, 3, 4, 5]
list.clear()
print(list)  # Output: []

Example of everyday applications that use lists in Python

  • Trello: one of the most used workspaces by any company today, it allows you to organize projects and cards into ordered lists.
  • Evernote: notes app that lets you create to-do lists and organize information into structured lists.
  • Spotify: uses playlists to allow users to create and organize their own music collections.
  • WhatsApp: displays conversations in list form, allowing users to view and respond to messages.
  • Google Keep: Notes and reminders app that uses lists to help users organize tasks, ideas, and reminders.
  • Amazon: Uses lists to represent shopping carts, wish lists, and order history.
  • Google Calendar: Allows you to schedule events and appointments in a list or calendar view.
  • Contacts: Contact management on mobile devices that uses lists to store and organize contact information such as names, phone numbers, and email addresses.

Cons of using list Python

Although we’ve already talked about its pros, as with any programming language, programming and creating lists in Python has its cons. Read below about some of them.

Performance

Compared to data structures like arrays or sets, lists can perform poorly in some specific operations. This is because lists in Python are implemented as dynamic arrays, which can result in slower execution time for things like inserting and deleting in middle positions in the list.

Fixed size vs dynamic size

In some situations you may need to work with a fixed size of data , where you know the composition and it doesn’t change. In these situations, an array can be more efficient and take up less memory space than a list.

efficient search

If you need to perform frequent searches on a large list, using other data structures such as dictionaries or sets may be more efficient. These structures offer a faster search time compared to linear search in a list.

Immutability

In Python, lists are mutable, allowing elements to be changed, added, or removed. However, in some scenarios, it is necessary to deal with immutable data, where elements cannot be modified after creation. In these cases, tuples may be more suitable, as they do not allow changes to elements after their creation.

memory usage

Lists in Python can consume more memory than other data structures, especially when complex objects or lots of data are present in them. This can become a concern on memory-constrained systems.

Conclusion

In short, any type of application benefits from using lists in Python. The manipulation, creation and modification of them are simple and practical, as demonstrated in this article. However, it is important to consider the need for its use, as in certain situations it may be unnecessary.

Therefore, when developing your application, initially check which language is most suitable. As mentioned earlier in the cons section, it’s important to note that using lists in Python can increase processing load and waiting time for processing the required data.

Remembering that no job is irreversible is important. Starting something in Python won’t give you problems that you can’t handle. Our advice is to avoid wasting time and setbacks. In programming, time is really important, and you can save it with planning and constant study.

Was this helpful?

Thanks for your feedback!

Schenia T

Data scientist, passionate about technology tools and games. Undergraduate student in Statistics at UFPB. Her hobby is binge-watching series, enjoying good music working or cooking, going to the movies and learning new things!

Leave a Reply

Your email address will not be published. Required fields are marked *