Чем отличается список от множества python
Перейти к содержимому

Чем отличается список от множества python

  • автор:

What is the difference between sets and lists in Python?

Is the only difference between sets and lists in Python the fact that you can use the union, intersect, difference, symmetric difference functions to compare two sets? Why can’t these functions simply be applied to lists? In what situations are sets more useful than lists?

DSM's user avatar

7 Answers 7

There’s a huge difference.

  1. Sets can’t contain duplicates
  2. Sets are unordered
  3. In order to find an element in a set, a hash lookup is used (which is why sets are unordered). This makes __contains__ ( in operator) a lot more efficient for sets than lists.
  4. Sets can only contain hashable items (see #3). If you try: set(([1],[2])) you’ll get a TypeError .

In practical applications, lists are very nice to sort and have order while sets are nice to use when you don’t want duplicates and don’t care about order.

Also note that if you don’t care about order, etc, you can use

to get the intersection between a set and a list .

mgilson's user avatar

sets — Unordered collections of unique elements

lists — ordered collections of elements

sets allows you to do operations such as intersection , union , difference , and symmetric difference , i.e operations of math’s set theory. Sets doesn’t allow indexing and are implemented on hash tables.

lists are really variable-length arrays, not Lisp-style linked lists. In lists the elements are accessed by indices.

Ashwini Chaudhary's user avatar

Set

A set is a collection which is unordered and unindexed, and doesnt allow duplicates. In Python, sets are written with curly brackets.

  • You cannot access items in a set by referring to an index
  • Sets are mutable
  • They are useful for checking for duplicates

List

A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

  • You access the list items by referring to the index number
  • Lists are mutable.

benzkji's user avatar

Set represents a collection of distinct elements. In python, sets are mainly used for two reasons (Book: Data Science from Scratch, Joel Gruce):

For faster operation: in is a very fast operation on sets. If we have a large collection of elements and if we wish to perform membership test, in that case it is appropriate to use set instead of a list.

To find a distinct items in a collections. Programmers use sets much less frequently than dicts and lists.

Sayali Sonawane's user avatar

Some more differences are:

  1. List can be 2-D whereas a set can’t.
  2. As list are ordered (IE. have serial number) list are comparatively slow to execute whereas sets are fast.
  3. List in python is like Array of java or c.
  4. Printing a set almost always provide different sequence of output.
  5. Set uses hash function to find an element whereas list is an array. Hence finding element in Set is faster than in list .

BlackBeard's user avatar

Actually there are four collection data types of in python:

List is a collection which is ordered and changeable. Allows duplicate members.

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Set is a collection which is unordered and unindexed. No duplicate members.

Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

You can access a list item by referring to its index. however, in sets, you need to loop through the set items in order to access it.

Soft_Coder's user avatar

Difference Between Sets and Lists Here we will discuss the difference between Sets and List in Python.

Lists 1) Lists save elements in the order they are inserted. 2) Lists support indexing. 3) We can change the value of the element stored in the lists. 4) Lists can store duplicate values. 5) Lists are declared using square brackets. 6) Example: A = [1, 2, 3, 4, 5, 1, 2, 3]

Sets 1) Sets do not save elements in the order they are inserted. 2) Sets do not support indexing. 3) We cannot change the value of the element stored in the sets. 4) Sets cannot store duplicate values. 5) Sets are declared using curly brackets. 6) Example: A =

Осваиваем Python. Унция 1. Типы данных.

Продолжаю своё начинание. Данная статья является логическим продолжением первой. Было приятно читать ваши комментарии. Я надеялся, что данный цикл статей окажется для кого-то полезным, но совершенно не предполагал, что заинтересовавшихся будет довольно большое количество. Это заставляет относится к делу серьёзнее и ответственнее.
Без лишних слов, сразу к делу.

  • Числа
  • Строки
  • Кортежи
  • Списки
  • Словари
  • Множества
Числа, строки и кортежи

Причина того, что эти типы оказались сведёнными в один раздел, кроется в одном очень важном моменте. Без понимания которого можно допустить трудно обнаруживаемые ошибки. Дело в том, что данные типы в отличии от списков и словарей являются неизменяемыми объектами. Т.е. создав их однажды — изменить их значение не представляется возможным. Возникает справедливый вопрос: каким тогда образом работают следующие инструкции?

Инструкция x = 2 создаёт числовой объект со значением 2 и присваивает ссылку на этот объект переменной x. Далее инструкция x = 3 создаёт новый числовой объект со значением 3 и присваивает ссылку на него переменной x. А объект со значением 2 удаляется из памяти автоматическим сборщиком мусора т.к. была потеряна последняя ссылка на этот объект.
Благодаря этому справедливо следующее:

>>> x = y = 3 # переменные x и y содержат одну и ту же ссылку на объект 3
>>> x = 2 # переменная x теперь содержит ссылку на другой объект 2
>>> x
2
>>> y # y по-прежнему ссылается на объект 3
3

В тему будет упомянуть про оператор is. Этот оператор возвращает значение True, когда слева и справа от него находятся переменные содержащие указатели на один и тот же объект. Возникает вопрос о странном поведении этого оператора:
>>> x = 2
>>> y = 2 # создано два разных объекта
>>> x is y # по идее должно быть возвращено значение False
True

Здесь дело в кэширующих внутренних механизмах самого интерпретатора. Для оптимизации скорости выполнения при объявлении числового или короткого строкового объекта — в кэше создаётся пара ссылка и значение. И в дальнейшем при объявлении такого же объекта — не создаётся новый объект, а используется уже созданный. Напрашивается вывод о несостоятельности использования оператора is для числовых и строковых типов данных.

  • целые числа неограниченной длины — интерпретатор сам определит необходимость использования объектов неограниченной длины и сделает необходимые преобразования. Более нет необходимости следить за переполнениями.
  • Числа с плавающей точкой
  • восьмеричные и шестнадцатеричные числа
  • комплексные числа

>>> print 2 ** 150 # 2 в степени 150
1427247692705959881058285969449495136382746624
>>> print int(5.89),round(5.89),round(5.89,1) # округление вниз, вверх, с точностью до 1 знака
5 6.0 5.9
>>> import math
>>> math.pi
3.1415926535897931
>>> print math.sin(math.pi/2)
1.0
>>> import random
>>> random.randint(1,100) # случайное целое число в диапазоне от 1 до 100
19

Строки:

Строки в апострофах и в кавычках — это одно и то же
Строки в тройных кавычках — в тройные кавычки можно заключить целый блок строк, например целиком HTML или XML документ.
Неформатированные строки — строки вида r«\n\t» — последовательности в такой строке не будут заменены на спец. Символы
Строки символов юникода — u’string’ # теряет актуальность в версии 3.0 подробнее об изменениях 3.0

Базовые операции над строками:

>>> print str(len(‘string’))*3 # len() — возвращает количество символов в строке
666 # * — перегруженый оператор, делающий повтор строки указанное число раз
>>> ‘r’ in ‘string’ # оператор in возвращает True если подстрока найдена в строке
True
>>> ‘string’.replace(‘r’,») # замена одной подстроки на другую
‘sting’
>>> ‘string’.find(‘ri’) # возвращает номер смещения искомой подстроки
2
>>> ‘a,b,c’.split(‘,’) # функция разделения на подстроки по указанному символу или подстроке
[‘a’, ‘b’, ‘c’]
Более полную информацию о строковых методах можно получить, введя в интерактивном режиме команду help(str).
Так же строки уже были описаны моим будущим соавтором этого цикла статей тут

Индексирование, выборка и срезы последовательностей данных.

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

>>> ‘string'[1]
‘t’
>>> ‘string'[-2] # второй элемент с конца строки
‘n’

Срез — достаточно мощный инструмент выборки данных из последовательностей, который используется не только в строках но и в коллекциях, речь о которых пойдёт в этой статье чуть ниже.
Общий вид:
S[i:j:h], где S — строка, i — значение смещения, левая граница (включительно), j — значение смещения, правая граница (она не входит в срез), h — значение шага.
Примеры:

Говоря о строках, конечно, нельзя забыть о регулярных выражениях. В Python для их использования необходимо импортировать модуль re
Я надеюсь, что о них удастся поговорить отдельно.

Кортежи

Кортеж — это упорядоченная, неизменяемая коллекция объектов произвольных типов, поддерживающая произвольное число уровней вложенности.
Основы синтаксиса так же уже описывал cleg в статье

Списки и словари

Списки и словари являются изменяемыми встроенными типами данных. А это значит, если возвращаться к тому с чего мы начали разговор, что, если создать список Y, затем сделать присваивание X=Y, а затем изменить X, то Y тоже изменится. За этим нужно внимательно следить! Для того, чтобы этого не происходило, необходимо создать новый объект эквивалентный исходному, например, так: X=Y[:]
Иллюстрация:

Или, если требуется обеспечить неизменность созданного объекта — использовать вместо списков кортежи.

  • операции над последовательностями неприменимы к словарям т.к. словари — это не последовательность, а отображение.
  • Ключи не обязательно должны быть строками. В роли ключей могут выступать любые неизменяемые объекты. Т.е. если рассматривать встроенные типы данных, то — это числа, строки и кортежи. Ясно, что при использования чисел, словарь превращается в подобие списка, однако, остаётся при этом неупорядоченным. Используя в качестве ключа кортежи, появляется возможность использовать составные ключи. Экземпляры пользовательских классов так же могут выступать в качестве ключей при условии, что они реализуют определённые методы указывающие интерпретатору на то, что объект является неизменяемым.
Множества

Множества — это контейнеры для других объектов. Множества создаются встроенной функцией set и поддерживают типичные математические операции над множествами

Элементами множества могут стать любые неизменяемые объекты.
После того, как мы проделали определённые операции над множествами — их можно разместить обратно в список, например, так:

На этом всё на сегодня.
Пользуясь терминологией Радио-Т хочется задать вопрос 🙂 Куда подкрутить градус гиковости, по вашему мнению? Если вверх, то на мой взгляд, циклы и ветвления стоит раскрыть только с точки зрения особенностей присущих Python.
Спасибо за внимание! Мы продолжим 🙂

Tuples vs. Lists vs. Sets in Python

In Python, there are four built-in data types that we can use to store collections of data. With different qualities and characteristics, these built-in data types are List ( list ), Tuple (tuple), Set ( set ), and Dictionary ( dict ).

In this article, we are going to dig into the rabbit holes of Lists, Tuple, and Sets in Python. We will go through their differences and when to use these data types.

As Dictionary associates keys with their respective values, which is a very different use case compared to List, Tuple, and Set (which simply just contain values), it won’t be part of this discussion.

For the sake of simplicity, I will use Set and Dictionary interchangeably, as they are based on Hash Table (or Hash Map).

Python built-in data types to store collections of dataPython built-in data types to store collections of data

Why do we care?

For the most part, these data types can be used interchangeably within an application without much trouble.

Yet, imagine if we were given a task to check if a needle exists in a sizable haystack. What would be the most efficient way in terms of speed and memory to do so?

Should the haystack be a List? What about a Tuple? Or why not always use a Set (or a Dictionary)? What are the caveats that we should look out for?

Differences between List, Tuple, and Set

Duplicates

If I were to explain this, List and Tuple are like siblings in Python. On the other hand, Set (or Dictionary) is like a cousin to both of them.

Unlike a List or Tuple, a Set cannot contain duplicates. In other words, the elements in a Set are unique.

With this knowledge in mind, we now know that Set can also be used to remove duplicates from a list!

Sorting Order

You might have heard the statement “Set and Dictionary are not ordered in Python.” Well, that is only half the truth today, depending on which version of Python you are using.

Before Python 3.6, Dictionaries and Sets do not keep their insertion order. Here’s an example if you try it out in Python 3.5:

Today, that statement is out of date by a couple of years. Starting from Python 3.7, Dictionary and Set are officially ordered by the time of insertion.

Anyway, in case you wondered, Lists and Tuples are ordered sequences of objects.

Mutability

When you describe an object as mutable, it’s simply a fancy way of saying the object’s internal state can be changed.

The key difference here is that Tuple is immutable (not changeable), whereas List and Set are mutable.

Although Sets are mutable, we cannot access or change any element of a Set via indexing or slicing. Hence, we can only add new elements into a set — not change them.

Do note that the update method in a Set simply means the ability to add multiple elements at once.

Indexing

Both Tuple and List support indexing and slicing, while Set does not.

When to use List vs. Tuple?

As we mentioned earlier, Tuples are immutable, whereas Lists are mutable. By the same token, Tuples are fixed size in nature, whereas Lists are dynamic.

Use List

  1. When you need to mutate your collection.
  2. When you need to remove or add new items to your collection of items.

Use Tuple

  1. If your data should or does not need to be changed.
  2. Tuples are faster than lists. We should use a Tuple instead of a List if we are defining a constant set of values and all we are ever going to do with it is iterate through it.
  3. If we need an array of elements to be used as dictionary keys, we can use Tuples. As Lists are mutable (unhashable type), they can never be used as dictionary keys.

When to use Set vs. List/Tuple?

As Set uses Hash Table as its underlying data structure, Set is blazingly fast when it comes to checking if an element is inside it (e.g. x in a_set ).

The idea behind it is that looking up an item in a hash table is an O(1) (constant time) operation.

«So, should I always use Set or Dictionary?»

Essentially, if you do not need to store duplicates, Set is going to be better than List. Period.

Summary

If you’re a numbers geek like me, check out this speed comparison between Tuple, List, and Set when iterating or checking if an object is present in a collection.

List, Set, Tuple, and Dictionary Data Structures in Python

List set tuple dictionary in python

Data Structure is a data storage format that allows for the efficient access and manipulation of the stored data. If the data is stored in a structured format, then it would be easy for a programming language to deal with it like accessing, searching, manipulating, etc.

In Python, the basic data structures include lists, sets, tuples, and dictionaries. Each of the data structures is unique in its own way. We will see all of them one by one.

Different Data Structures in Python

List

Lists are one of the simple and most commonly used data structures provided in python. It can store multiple data types at the same time like string, int, boolean, etc, and hence it is called heterogeneous.

Lists are mutable which means the data inside the list can be altered. Lists contain ordered data and can also contain duplicate values.

  • Heterogeneous
  • Mutable
  • Ordered
  • Can have duplicate value

Eg: mylist = [45, 37, ‘ABC’, 56, 89]

Tuple

Tuples are just like lists except that they are immutable which means data inside a tuple can only be accessed but cannot be altered.

  • Heterogeneous
  • Immutable
  • Ordered
  • Can have duplicate values

Eg: mytuple = (25, 30, 35, 40)

Set

Set is another data structure that holds a collection of unordered, iterable, and mutable data. But it only contains unique elements. They can contain multiple data types and hence are heterogeneous.

  • Heterogeneous
  • Mutable
  • Unordered

Dictionary

It is slightly different from other data structures in which data are stored in the form of key-value pairs. Keys inside the dictionaries should be unique whereas their value(s) need not necessarily be unique. Any data inside the dictionary can be accessed through its key.

  • Heterogeneous
  • Mutable
  • Unordered before Python v3.7, Ordered in Python v3.7 or more
  • Do not allow duplicate values

Working with Lists

There are lots of operations you can do with a list. As told above, a list is mutable, so you not just can access its data but also manipulate it. Let’s see it:

a) Creating a list and printing its data

b) List length

To determine how many items a list has, the len() function is used.

c) Accessing Items on a list

As lists are iterable, we can access any element(s) of a list through its index value. In Python, counting starts from 0. So to get the first element of the list we use the index 0 so on and so forth.

Accessing list items in a custom way

Getting from the last:

Will return the third, fourth, and fifth items:

Returning items from the beginning to a certain point: This excludes the last point

Returning items from a certain point to the last:

d) Changing list items

Changing one value with another value:

Changing multiple values with multiple values:

Changing one value with two new values:

Changing two values with one new value:

e) Adding items to a list

We can add new items to a list either at the last or at any position. To insert an item in the last position of a list we use the ‘append()’ function and to insert a new item at a particular position in a list, we use the ‘insert()’ function. See the example below:

We can also combine two lists as can be seen in below code:

f) Removing an item from a list

Just like adding an item to a list, we can also remove it either from the last as by default or from a specified position. Items can be deleted either by using their name or through their index value. Let’s see the example below.

g) Deleting the whole list or emptying its data

We can delete the whole list if needed or can just clear its data in python so easily. See the examples below:

Working with Sets

a) Creating a set and printing its data

b) Accessing Items of a set

Since data is not in an ordered manner, you cannot access items in a set by referring to an index or a key. Instead, you can loop through the set items using a for loop:

c) Adding an item in a set

In Python we have ‘add()’ method to do the adding the item in the set:

d) Adding two sets

We have ‘ update() ‘ method in Python to add items from another set into the current set:

e) Removing an item from a set

Using ‘remove()’ method:

Using ‘pop()’ method to remove a random item from a set:

f) Emptying all items from a set

To clear all the data stored in a set, we have the ‘clear()’ function in Python

g) Deleting the whole set

The 'del' keyword will delete the set completely:

Working with Tuples

a) Creating a tuple and printing its data

b) Accessing tuple items

Since tuples are ordered, we can access any element of the tuple by calling its position:

c) Updating the value of the tuple

Tuples are immutable. Once a tuple is created, you cannot change its values. If you try to change or add or delete the data of a tuple, it will throw an error. You can only access the data and nothing else. But there is a way. You can first change a tuple into a list, then perform any operation of the list and then convert back the list into the tuple. Let’s see.

Updating the tuple:

First, convert the tuple into a list and then perform updating operation.

Adding an item in the tuple:

First, convert the tuple into a list and then perform adding operation.

Removing an item from the tuple:

First, convert the tuple into a list and then perform the removing operation.

Working with Dictionary

a) Creating and printing data from a dictionary

b) Accessing Items from a dictionary

Since data in a dictionary is stored in the form of keys and their associated values, we can access the value by referring its key:

c) Updating values of a dictionary

d) Adding a new entry in a dictionary

We can easily add a new entry in a dictionary in Python. Just you have to provide the value to add with its key:

e) Removing an item from a dictionary

f) Clearing the values of a dictionary

We can clear the whole dictionary data in Python easily with ‘clear()’ functions or can even delete the whole dictionary.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *