Python operation on lists

Python List Explain with Examples

We will discuss the basics of lists in Python, from creation and manipulation to the various operations which can be performed on them. The list data structure is an ordered collection of items that provides efficient access and manipulation of individual elements.

Table of contents

  • 1. What is a List in Python?
    • 1.1 Example of List in Python
    • 1.2 Key Points of List
    • 2.1 list() – Create a List
    • 2.2 Create Lists using List Comprehension
    • 2.3 Create a Nested List
    • 3.1 Access the Elements of a Nested List
    • 5.1 Syntax of for loop on a list
    • 5.3 enumerate() and FOR Loop on a List
    • 8.1 Adding Elements to List
    • 8.2 Removing Elements From a List
    • 8.3 Concatenation of two Lists
    • 8.4 Sorting a List
    • 8.5 List Slicing

    1. What is a List in Python?

    Python list is an ordered collection of items that can contain elements of any data type, including other lists. It is a mutable data structure, meaning its contents can be modified after they have been created. In Python, Lists are typically used to store data that needs to be sorted, searched, or altered in some way. They can also be used to perform operations on a set of data quickly.

    1.1 Example of List in Python

    Following is a quick example of a list.

     # Create a list of numbers my_list = [1, 2, 3, 4] # Create a list of mixed datatypes my_list = [1, 'Hello', [1,2,3]] 

    1.2 Key Points of List

    1. Lists are mutable, meaning their contents can be modified after they have been created.
    2. Elements in a list can be accessed by their index.
    3. A list is an ordered collection of elements.
    4. Lists can contain elements of any data type, including other lists.

    2. Create a List in Python

    There are several different ways to create a list in Python. The most common is to use square brackets [] to enclose a comma-separated list of elements.

    2.1 list() – Create a List

    The list() function takes in an iterable object and creates a list from it. This means that any object which can be iterated over (for example, a string, a tuple, or a range) can be used to create a list.

    It is a convenient way to quickly create lists, as it requires no additional code. It can also be used to convert tuples and ranges into lists, which can be useful when working with such objects.

     # Creates a list from string my_list = list('Hello') print(my_list) # Creates a list using range() my_list = list(range(1, 5)) print(my_list) # Creates a list from tuple my_list = list((1, 2, 3)) print(my_list) 

    python lists

    To create an empty list, just use either empty square brackets [] or list().

    2.2 Create Lists using List Comprehension

    Python List Comprehension allows you to create a new list by applying an operation to each element in an existing iterable. List comprehensions are a concise, readable way to create new lists, and are often preferred over using a for loop and the append() method.

    For example, you can create a list of the squares of the numbers from 0 to 9 like this:

     # List Comprehension squares = [x**2 for x in range(10)] 

    List comprehension can be more memory-consuming when working with large datasets and it is not a good idea to use them for large datasets.

    2.3 Create a Nested List

    A nested list is a list that contains other lists as its elements. They are a versatile data structure that allows you to store a collection of lists within a single list in python.

     # Create nested list nested_list = [ ['Python', 'Java', 'C++'], ['JavaScript', 'TypeScript', 'Rust'], ['Go', 'Kotlin', 'Swift'] ] 

    3. Accessing Elements in a List

    In Python, list elements are indexed starting from 0, so the first element in a list has an index of 0, the second element has an index of 1, and so on.

     # Get element from list by index my_list = ['Python', 'Java', 'C++', 'JavaScript'] print(my_list[0]) # Output: # 'Python' 

    To access elements at the end of the list, you can use negative indexing, in which -1 represents the last element, -2 represents the second last, and so on.

     last_element= my_list[-1] print(last_element) # Output # 'Javascript' 

    3.1 Access the Elements of a Nested List

    In order to access the elements of a nested list, you need to use multiple sets of square brackets, with the first set referencing the outer list and the subsequent sets referencing the inner lists.

     # Create nested list nested_list = [ ['Python', 'Java', 'C++'], ['JavaScript', 'TypeScript', 'Rust'], ['Go', 'Kotlin', 'Swift'] ] # Index 0 of the outer list and Index 1 of the Inner list print(nested_list[0][1]) # Output: # Java 

    4. Different Data Types Allowed in a List

    A single Python list can contain elements of different data types, such as integers, strings, floats, booleans, and even other lists or other complex data types like tuples or objects of custom classes.

     # A list of integers numbers = [1, 2, 3, 4, 5] # A list of strings words = ['hello', 'world', 'foo', 'bar'] # A list of booleans flags = [True, False, True, False, True] # A list of mixed data types mixed_list = [1, 'hello', 3.14, True, [1, 2, 3]] # A list of lists nested_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] 

    5. Perform for Loop on a List

    You might have seen that the most common way to iterate over a list in Python is by using a for loop.

    5.1 Syntax of for loop on a list

     for item in my_list: # Code to be executed for each item 

    5.2 Example of for loop on a List

    Here is an example of how to use the for loop on a list in python.

     # For loop example to iterate list languages = ['Python','Java','C++','JavaScript'] for language in languages: print(language) # Ouput: # Python # Java # C++ # JavaScript 

    The above example prints each element in the list, but you can do any other operations in the loop as well depending on your use case like adding them to another list, performing some operation on it, and so on.

    5.3 enumerate() and FOR Loop on a List

    Another way of looping through list elements is by using enumerate() function which returns both the index and value of the list elements. This method is useful when you want to access index in for loop.

     # Iterate list using enumerate for index, language in enumerate(languages): print(f'. ') # Output # 1. Python # 2. Java # 3. C++ # 4. JavaScript 

    6. Python List Vs Python Array

    Python List is a built-in data structure whereas Arrays are not built-in. To use an array we need to import it using either the python NumPy module or we can use the python array module.

    The python array module is built in while the NumPy library is a third party and you need to install it before using it. Here is the main point that makes them unique. Depending on your case you can use any of them.

    Источник

    Списки (list). Функции и методы списков

    Python 3 логотип

    Сегодня я расскажу о таком типе данных, как списки, операциях над ними и методах, о генераторах списков и о применении списков.

    Что такое списки?

    Списки в Python — упорядоченные изменяемые коллекции объектов произвольных типов (почти как массив, но типы могут отличаться).

    Чтобы использовать списки, их нужно создать. Создать список можно несколькими способами. Например, можно обработать любой итерируемый объект (например, строку) встроенной функцией list:

    Список можно создать и при помощи литерала:

    Как видно из примера, список может содержать любое количество любых объектов (в том числе и вложенные списки), или не содержать ничего.

    И еще один способ создать список — это генераторы списков. Генератор списков — способ построить новый список, применяя выражение к каждому элементу последовательности. Генераторы списков очень похожи на цикл for.

    Возможна и более сложная конструкция генератора списков:

    Но в сложных случаях лучше пользоваться обычным циклом for для генерации списков.

    Функции и методы списков

    Создать создали, теперь нужно со списком что-то делать. Для списков доступны основные встроенные функции, а также методы списков.

    Таблица «методы списков»

    Метод Что делает
    list.append(x) Добавляет элемент в конец списка
    list.extend(L) Расширяет список list, добавляя в конец все элементы списка L
    list.insert(i, x) Вставляет на i-ый элемент значение x
    list.remove(x) Удаляет первый элемент в списке, имеющий значение x. ValueError, если такого элемента не существует
    list.pop([i]) Удаляет i-ый элемент и возвращает его. Если индекс не указан, удаляется последний элемент
    list.index(x, [start [, end]]) Возвращает положение первого элемента со значением x (при этом поиск ведется от start до end)
    list.count(x) Возвращает количество элементов со значением x
    list.sort(Python operation on lists) Сортирует список на основе функции
    list.reverse() Разворачивает список
    list.copy() Поверхностная копия списка
    list.clear() Очищает список

    Нужно отметить, что методы списков, в отличие от строковых методов, изменяют сам список, а потому результат выполнения не нужно записывать в эту переменную.

       И, напоследок, примеры работы со списками:

    Изредка, для увеличения производительности, списки заменяют гораздо менее гибкими массивами (хотя в таких случаях обычно используют сторонние библиотеки, например NumPy).

    Для вставки кода на Python в комментарий заключайте его в теги

    • Книги о Python
    • GUI (графический интерфейс пользователя)
    • Курсы Python
    • Модули
    • Новости мира Python
    • NumPy
    • Обработка данных
    • Основы программирования
    • Примеры программ
    • Типы данных в Python
    • Видео
    • Python для Web
    • Работа для Python-программистов

    Источник

    Читайте также:  Поле загрузки файлов, которое мы заслужили
Оцените статью