Python List & Set syntax recommendation

List vs Set commonly-used syntax inconsistencies

ListSet
>>> ls = [1, 2]
>>> ls.append(3)

>>> ls
[1, 2, 3]
>>> s = {1, 2}
>>> s.union({3})
{1, 2, 3}
>>> s
{1, 2}
>>> ls = [1, 2]
>>> ls.extend([3, 4])

>>> ls
[1, 2, 3, 4]
>>> s = {1, 2}
>>> s.union({3, 4})
{1, 2, 3, 4}
>>> s
{1, 2}
>>> ls = [1, 2]
>>> [x for x in ls if x in [2, 3]]
[2]
>>> ls
[1, 2]
>>> s = {1, 2}
>>> s.intersection({2, 3})
{2}
>>> s
{1, 2}

List:

  • Different syntax among union with 1
    or multiple elements, or intersection
  • Updates original list

Set:

  • Similar syntax for union and intersection
     
  • Never updates original set

List & Set common syntax recommendation if not in a loop

Warning
+ syntax copies all the elements from the old list to a new list, adds the new element(s), then assigns this new list to the variable.
In a loop, this syntax will result in O(n2) complexity.

ListSet
>>> ls = [1, 2]                   
>>> ls + [3]
[1, 2, 3]
>>> ls + [3, 4]
[1, 2, 3, 4]
>>> [x for x in ls if x in [2, 3]]
[2]
>>> ls
[1, 2]
>>> s = {1, 2}                    
>>> s | {3}
{1, 2, 3}
>>> s | {3, 4}
{1, 2, 3, 4}
>>> s & {2, 3}
{2}
>>> s
{1, 2}
  • Similar syntax for both List and Set
  • Original list or set is never updated

Last modified on 2024-09-02