Python list set разница

Python Lists, Tuples, and Sets: What’s the Difference?

In Python, we have four built-in data structures that can store a collection of different elements. These are lists, dictionaries, tuples, and sets. If you already know the theory behind these data structures, you can go to our Python Data Structures in Practice course and get hands-on experience with the most frequent ways they’re used. In this article, we’ll focus on Python lists, tuples, and sets and explore their similarities and differences.

Python Lists

A Python list is a built-in data structure that holds a collection of items. To understand how lists work, let’s go straight to the example.

We want to create a list that includes names of the US presidents elected in the last six presidential elections. List elements should be enclosed in square brackets [] and separated by a comma. To create a list, we can simply write elements in square brackets:

us_presidents_list = ['Joe Biden', 'Donald Trump', 'Barack Obama', 'Barack Obama', 'George W. Bush', 'George W. Bush']

The elements of this list appear in a specific order and start from the current president. If a president was elected twice (served for two terms), we include him twice. Here, we leverage two important characteristics of lists: lists are ordered and can contain duplicates.

When working with a list, you can iterate over it, access its elements, and also add, change, and remove list elements. These are the basic techniques that you can learn in our Python Data Structures in Practice course. Now, let’s go through a couple of examples:

    Iterating over the list. By iterating over the list, we can perform a particular operation (e.g. print ) with each element of the list:

for president in us_presidents_list: print(president) Output: Joe Biden Donald Trump Barack Obama Barack Obama George W. Bush George W. Bush

Here, we have printed out each element separately. By iterating over the list, we could also change all names to uppercase or extract last names into a separate list.

print(us_presidents_list[1]) Output: Donald Trump
us_presidents_list.append('Bill Clinton') print(us_presidents_list) Output: ['Joe Biden', 'Donald Trump', 'Barack Obama', 'Barack Obama', 'George W. Bush', 'George W. Bush', 'Bill Clinton']
us_presidents_list.remove('Bill Clinton') print(us_presidents_list) Output: ['Joe Biden', 'Donald Trump', 'Barack Obama', 'Barack Obama', 'George W. Bush', 'George W. Bush']
us_presidents_list[4] = 'George Bush' print(us_presidents_list) Output: ['Joe Biden', 'Donald Trump', 'Barack Obama', 'Barack Obama', 'George Bush', 'George W. Bush']

If you work a lot with numerical data, you may want to use arrays rather than lists. Learn how Python lists are different from arrays in this article.

Читайте также:  PHP MVC Frameworks - Search Engine

Python Tuples

A Python tuple is another built-in data structure that can hold a collection of elements. Tuples are technically very similar to lists. However, they usually have different applications; while lists mainly contain a collection of different items, tuple elements often correspond to one record.

For example, it would be more common to store basic information about one US president (rather than a list of US presidents) in one tuple. So, let’s create a us_president_tuple . A tuple can be created by placing all the elements inside parentheses (), separated by commas:

us_president_tuple = ('Joe', 'Biden', '2021-01-20', 'Democratic')

Here, we have included the president’s first name, last name, date of inauguration, and political party. These elements appear in a specific order – tuples are ordered. We don’t have duplicate elements in our tuple, but you can store duplicates in Python tuples.

Now, let’s perform some basic operations with our tuple. We can iterate over it and access its elements with indexing:

    Iterating over the tuple. Like with lists, we can print out each element of our tuple separately by iterating over it:

for i in us_president_tuple: print(i) Output: Joe Biden 2021-01-20 Democratic
print(us_president_tuple[2]) Output: 2021-01-20

Using index 2, we’ve printed out the third element of the tuple, which is the inauguration date. By accessing tuple elements, we can also get the full name of the current US president:

print(us_president_tuple[0], ‘ ‘, us_president_tuple[1]) Output: Joe Biden

Unlike lists, tuples are immutable. This data structure doesn’t allow changing, adding, or removing individual elements.

Python Sets

A Python set is a built-in data structure in Python that, like lists and tuples, holds multiple elements. To understand how it’s different from lists and tuples, let’s go through another example.

We’ll create a set called us_presidents_set with the names of US presidents. One of the ways to create a Python set is to define it with curly braces <>:

The names of five US presidents are included in random order because sets are unordered. Also, sets cannot contain duplicates; thus, all the names are included only once, no matter how many terms that person served as president.

Let’s have a couple of code examples to see how sets work in practice.

    Iterating over the set. We can iterate over a set to print its elements using the exact same code snippet we used with lists:

for president in us_presidents_set: print(president) Output: George W. Bush Joe Biden Bill Clinton Donald Trump Barack Obama

Note that the order of the elements printed in the output is different from the order we specified when creating this set. That’s because, as we mentioned, sets are an unordered collection of items. We may also iterate over this set to check whether we have ‘Ronald Reagan’ in the set.

reagan = False for president in us_presidents: if president == 'Ronald Reagan': reagan = True print(reagan) Output: False

us_presidents_set.add(‘George H. W. Bush’) print(us_presidents_set) Output:
us_presidents_set.remove(‘Bill Clinton’) print(us_presidents_set) Output:

Читайте также:  Java util functions predicate

Learn more about Python set operations in this comprehensive guide.

Wrap-Up: The Difference Between Lists, Tuples, and Sets in Python

Now, let’s summarize what we’ve learned so far about Python lists, tuples, and sets:

Python lists Python tuples Python sets
list = [item1, item2, item3] tuple = (item1, item2, item3) set =
ordered ordered unordered
allow duplicates allow duplicates no duplicates
mutable immutable mutable

These are the basic characteristics of Python lists, tuples, and sets. There are more features that can influence which data structure is preferable for a particular application. Also, do not forget about Python dictionaries, yet another built-in data structure that can hold a collection of items.

To learn more about lists, tuples, sets, and dictionaries, check out our interactive Python Data Structures in Practice course. It contains 118 exercises that cover typical use cases for each of the data structures discussed in this article. You’ll also learn about nested lists, which can be used to represent 2D images, tabular data, or virtual game boards. At the end of the course, you’ll write an actual PC game!

For those willing to take a comprehensive approach to learning Python, we recommend the track Learn Programming with Python. It includes five fully interactive courses that cover Python basics and some more advanced topics.

Still not sure if you need to learn Python? Read this article to see why Python is your must-learn in 2021.

Thanks for reading and happy learning!

Источник

Чем отличаются list, tuple и set? Зачем они нужны?

List (список), tuple (кортеж), set (множество) — это встроенные структуры данных языка python. Каждая из них имеет свои возможности и ограничения. Это позволяет выбрать наиболее подходящий способ хранения информации в программе.

List (список)

Базовая структура данных в python. Элементы в списке хранятся последовательно, каждому из них присвоены индексы, начиная с нуля. В отличие от массива, список может хранить объекты любого типа.

Создание списка

>>> my_list = [] # Создание пустого списка с помощью литерала списка >>> my_list = list() # Создание пустого списка с помощью встроенной функции >>> >>> my_list = [1,2,['a','b'],4,5] # Инициализация списка >>> >>> my_list = list('hello world') # Создание списка из итерируемого объекта >>> my_list ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> >>> my_list = [x for x in range(10)] # Генератор списков в действии >>> my_list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Доступные методы

  • my_list.append(x) — добавляет x в конец списка
  • my_list.clear() — очищает список
  • my_list.copy() — возвращает копию списка my_list
  • my_list.count(x) — возвращает кол-во элементов со значением x
  • my_list.extend(x) — добавляет элементы списка x к концу списка my_list
  • my_list.index(x,start,end) — возвращает индекс первого найденного x, можно задать промежуток для поиска (опционально)
  • my_list.insert(index, x) — вставляет x на заданную позицию
  • my_list.pop(index) — возвращает элемент с указанным индексом и удаляет его, если индекс не указан — возвращается и удаляется последний элемент
  • my_list.remove(x) — удаляет первый элемент со значением x
  • my_list.reverse() — инвертирует порядок элементов в списке
  • my_list.sort(key=x) сортирует список на основе функции x

В каких случаях использовать?

Для хранения элементов, объединенных каким либо признаком. В случае, если изменение элементов и/или расширение списка не предполагается, следует использовать неизменяемый аналог — кортеж.

Tuple (кортёж)

Кортеж — это неизменяемый и более быстрый аналог списка. Он защищает хранимые данные от непреднамеренных изменений и может использоваться в качестве ключа в словарях (словарь — ассоциативный массив в python).

Создание кортежа.

>>> my_tuple = () # Создание кортежа с помощью литерала >>> my_tuple = tuple() # Создание кортежа с помощью встроенной функции >>> >>> my_tuple = (1,2,['a','b'],4,5) # Инициализация кортежа >>> >>> my_tuple = tuple('hello world') # Создание кортежа из итерируемого объекта >>> my_tuple ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd') >>> >>> my_tuple = tuple(2**x for x in [0, 1, 2, 3]) # Генератор кортежей >>> my_tuple (1, 2, 4, 8) 

Доступные методы

  • my_tuple.count(x) — возвращает кол-во элементов со значением x
  • my_tuple.index(x,start,end) — возвращает индекс первого найденного x, можно задать промежуток для поиска (опционально)

В каких случаях использовать?

Для хранения данных вместо списка (если они не предполагают изменений).

Set (множество)

Множество — это набор уникальных элементов в случайном порядке (неупорядоченный список). Множества примечательны тем, что операция проверки “принадлежит ли объект множеству” происходит значительно быстрее аналогичных операций в других структурах данных.

Создание множества

>>> my_something = > # . Попытка создать множество при помощи литерала даст нам словарь >>> type(my_something) class 'dict'> >>> >>> my_set = set() # Создание при помощи встроенной функции >>> >>> my_set = 1,2,3,4,5> # Инициализация множества >>> >>> my_set = set('hello world') # Создания множества из итерируемого объекта >>> my_set 'r', 'o', 'e', 'h', 'd', 'w', 'l', ' '> >>> >>> my_set = x for x in range(10)> # Генератор множеств >>> my_set 0, 1, 2, 3, 4, 5, 6, 7, 8, 9> 

Доступные методы

  • my_set.add(x) — добавляет x во множество
  • my_set.difference(x) — возвращает множество элементов my_set, которые не входят во множество x
  • my_set.difference_update(x) — удаляет из множества my_set все элементы, которые входят во множество x
  • my_set.discard(x) — удаляет элемент x из my_set
  • my_set.intersection(x) — возвращает элементы общие для множеств my_set и x
  • my_set.intersection_update(x) — удаляет из множества my_set элементы, которых нет во множестве x
  • my_set.isdisjoint(x) — возвращает true если my_set и x не содержат одинаковых значений
  • my_set.issubset(x) — возвращает true если все элементы my_set входят во множество x
  • my_set.issuperset(x) — возвращает true если все элементы x входят во множество my_set
  • my_set.pop() — возвращает и удаляет первый (на данный момент) элемент множества
  • my_set.remove(x) — удаляет x из множества
  • my_set.symmetric_difference(x) — возвращает все элементы из x и my_set, которые встречаются только в одном из множеств
  • my_set.symmetric_difference_update(x) — обновляет исходное множество таким образом, что оно будет состоять из всех элементов x и my_set, которые встречаются только в одном из множеств
  • my_set.union(x) — возвращает новое множество, состоящее из всех элементов x и my_set
  • my_set.update(x) — добавляет в my_set все элементы x

В каких случаях использовать?

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

Попробуйте бесплатные уроки по Python

Получите крутое код-ревью от практикующих программистов с разбором ошибок и рекомендациями, на что обратить внимание — бесплатно.

Переходите на страницу учебных модулей «Девмана» и выбирайте тему.

Источник

Оцените статью