2. List, Set, Tuple

2024. 3. 14. 01:07·Python

 

 

 
 

Lists¶

 
 

Lists group together data -- the data can be a mix of integers, floating point or complex numbers, strings, or other objects (including other lists).

 
In [2]:
a = [1, 2.0, "my list", 4]
 
In [3]:
print(a)
 
 
[1, 2.0, 'my list', 4]
 
In [4]:
type(a)
 
Out[4]:
list
 
In [5]:
print(a[2])     # remember, 0-based indexing
 
 
my list
 
In [6]:
b = ['another string']
a + b
 
Out[6]:
[1, 2.0, 'my list', 4, 'another string']
 
In [7]:
print(a*2)
 
 
[1, 2.0, 'my list', 4, 1, 2.0, 'my list', 4]
 
In [8]:
print(len(a))
 
 
4
 
 

Lists are mutable. You can change elements in a list.

 
In [9]:
a[1] = -2.0
a
 
Out[9]:
[1, -2.0, 'my list', 4]
 
In [10]:
a = [1, 2.0, "my list", 4]
a[0] = [-1, -2.1]
a[1:2] =[2,3]
a
 
Out[10]:
[[-1, -2.1], 2, 3, 'my list', 4]
 
In [11]:
a = [1, 2.0, "my list", 4]
a[0:1] = [-1, -2.1]   # this will put two items in the spot where 1 existed before
a
 
Out[11]:
[-1, -2.1, 2.0, 'my list', 4]
 
 

Just like everything else in python, a list is an object that is the instance of a class. Classes have methods (functions) that know how to operate on an object of that class.

There are lots of methods that work on lists. See the Python Tutorial.

 
In [12]:
help(list)
 
 
Help on class list in module builtins:

class list(object)
 |  list(iterable=(), /)
 |  
 |  Built-in mutable sequence.
 |  
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(self, /)
 |      Return a reverse iterator over the list.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(self, /)
 |      Return the size of the list in memory, in bytes.
 |  
 |  append(self, object, /)
 |      Append object to the end of the list.
 |  
 |  clear(self, /)
 |      Remove all items from list.
 |  
 |  copy(self, /)
 |      Return a shallow copy of the list.
 |  
 |  count(self, value, /)
 |      Return number of occurrences of value.
 |  
 |  extend(self, iterable, /)
 |      Extend list by appending elements from the iterable.
 |  
 |  index(self, value, start=0, stop=9223372036854775807, /)
 |      Return first index of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  insert(self, index, object, /)
 |      Insert object before index.
 |  
 |  pop(self, index=-1, /)
 |      Remove and return item at index (default last).
 |      
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(self, value, /)
 |      Remove first occurrence of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(self, /)
 |      Reverse *IN PLACE*.
 |  
 |  sort(self, /, *, key=None, reverse=False)
 |      Sort the list in ascending order and return None.
 |      
 |      The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
 |      order of two equal elements is maintained).
 |      
 |      If a key function is given, apply it once to each list item and sort them,
 |      ascending or descending, according to their function values.
 |      
 |      The reverse flag can be set to sort in descending order.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  __class_getitem__(...) from builtins.type
 |      See PEP 585
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

 
 

We can start with an empty list and build a list from there.

 
In [13]:
my_list = []
my_list.append(200.0)
my_list.append(-1.0)
my_list.append(-1.0)
my_list.append(3.14)
my_list.append(27)
my_list
 
Out[13]:
[200.0, -1.0, -1.0, 3.14, 27]
 
In [14]:
print(my_list.count(-1.0))
 
 
2
 
In [15]:
my_list.sort(reverse=True)
my_list
 
Out[15]:
[200.0, 27, 3.14, -1.0, -1.0]
 
In [16]:
help(a.insert)
 
 
Help on built-in function insert:

insert(index, object, /) method of builtins.list instance
    Insert object before index.

 
In [17]:
print(a)
 
 
[-1, -2.1, 2.0, 'my list', 4]
 
In [18]:
a.insert(3, "my inserted element")
 
In [19]:
a
 
Out[19]:
[-1, -2.1, 2.0, 'my inserted element', 'my list', 4]
 
 

We can use list as a stack using append and pop.

 
In [20]:
a.append(6)
a
 
Out[20]:
[-1, -2.1, 2.0, 'my inserted element', 'my list', 4, 6]
 
In [21]:
a.pop()
 
Out[21]:
6
 
In [22]:
a
# queue -> first in last out
 
Out[22]:
[-1, -2.1, 2.0, 'my inserted element', 'my list', 4]
 
 

Note that it is inefficient to use list as a queue. For queues, use collections.deque instead, which supports append and popleft methods.

 
 

Dictionaries¶

 
 

A dictionary stores data as a key:value pair. Unlike a list where you have a particular order, the keys in a dictionary allow you to access information anywhere easily.

 
In [23]:
my_dict = {"key1":1, "key2":2, "key3":3}
 
In [24]:
type(my_dict)
 
Out[24]:
dict
 
In [25]:
print(my_dict["key1"])
 
 
1
 
 

Dictionary is also mutable. You can add a new key:value pair; both can be of any type.

 
In [26]:
my_dict['key4'] = "new2"
print(my_dict)
 
 
{'key1': 1, 'key2': 2, 'key3': 3, 'key4': 'new2'}
 
 

Note that a dictionary is unordered.

You can also easily get the list of keys that are defined in a dictionary ...

 
In [27]:
keys = list(my_dict.keys())
print(keys)
 
 
['key1', 'key2', 'key3', 'key4']
 
In [28]:
type(keys)
 
Out[28]:
list
 
 

and check easily whether a key exists in the dictionary

 
In [29]:
print("key1" in my_dict)
print("invalidKey" in my_dict)
 
 
True
False
 
 

If a key does not exist, you cannot use it as a right value. For example, the following code would result in an error, which we will address later.

 
In [30]:
my_dict["invalidKey"] # This statement generates an error
 
 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In [30], line 1
----> 1 my_dict["invalidKey"]

KeyError: 'invalidKey'
 
 

Sets¶

 
 

A set is similar to a list, but contains unordered unique elements.

 
In [ ]:
s = {1, 2, 2, 4}
s
 
Out[ ]:
{1, 2, 4}
 
In [ ]:
type(s)
 
Out[ ]:
set
 
In [ ]:
t = {2, 7, 8, 9}
print(s.union(t))
print(s)
 
 
{1, 2, 4, 7, 8, 9}
{1, 2, 4}
 
In [ ]:
help(set)
 
 
Help on class set in module builtins:

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |  
 |  Build an unordered collection of unique elements.
 |  
 |  Methods defined here:
 |  
 |  __and__(self, value, /)
 |      Return self&value.
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iand__(self, value, /)
 |      Return self&=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __ior__(self, value, /)
 |      Return self|=value.
 |  
 |  __isub__(self, value, /)
 |      Return self-=value.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __ixor__(self, value, /)
 |      Return self^=value.
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __rand__(self, value, /)
 |      Return value&self.
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rxor__(self, value, /)
 |      Return value^self.
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __xor__(self, value, /)
 |      Return self^value.
 |  
 |  add(...)
 |      Add an element to a set.
 |      
 |      This has no effect if the element is already present.
 |  
 |  clear(...)
 |      Remove all elements from this set.
 |  
 |  copy(...)
 |      Return a shallow copy of a set.
 |  
 |  difference(...)
 |      Return the difference of two or more sets as a new set.
 |      
 |      (i.e. all elements that are in this set but not the others.)
 |  
 |  difference_update(...)
 |      Remove all elements of another set from this set.
 |  
 |  discard(...)
 |      Remove an element from a set if it is a member.
 |      
 |      If the element is not a member, do nothing.
 |  
 |  intersection(...)
 |      Return the intersection of two sets as a new set.
 |      
 |      (i.e. all elements that are in both sets.)
 |  
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |  
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |  
 |  issubset(...)
 |      Report whether another set contains this set.
 |  
 |  issuperset(...)
 |      Report whether this set contains another set.
 |  
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |  
 |  remove(...)
 |      Remove an element from a set; it must be a member.
 |      
 |      If the element is not a member, raise a KeyError.
 |  
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |      
 |      (i.e. all elements that are in exactly one of the sets.)
 |  
 |  symmetric_difference_update(...)
 |      Update a set with the symmetric difference of itself and another.
 |  
 |  union(...)
 |      Return the union of sets as a new set.
 |      
 |      (i.e. all elements that are in either set.)
 |  
 |  update(...)
 |      Update a set with the union of itself and others.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

 
 

Tuples¶

 
 

A tuple is similar to a list, but is immutable. It cannot be changed.

 
In [ ]:
a = (1, 2, 3, 4)
 
In [ ]:
print(a)
print(type(a))
 
 
(1, 2, 3, 4)
<class 'tuple'>
 
 

A tuple is convenient for assigning multiple variables concurrently.

 
In [ ]:
w, x, y, z = (1, 2, 3, 4)
 
In [ ]:
print(w, x, y, z)
 
 
1 2 3 4
 
In [ ]:
w, x = x, w  # swap w and x
print(w, x)
 
 
2 1
 
 

A tuple is immutable.

 
In [ ]:
a[0] = 2
 
 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-53-fa1ba3f7cc8f> in <module>
----> 1 a[0] = 2

TypeError: 'tuple' object does not support item assignment
 
 

We will discuss about error handling shortly.

 
 

Assignment, Shallow Copy, and Deep Copy¶

 
 

Assigment statement in Python may seem counterintuitive at first.

For immutable objects of basic types (numbers and strings), assignment copies the value; for other objects (such as a list or tuple), assignment creates an "alias" of the object.

See visualization here.

 
In [ ]:
# Assignment of immutable objects means copying
x = 'abc'
y = x
y = 'def'
print (x, y)

# Assignment of mutable objects means aliasing
a = [-1, -2.1, -2.0, 'my list', 4]
b = a  # this is just a pointer, both a and b refer to the same list object in memory
print(a)
a[0] = "changed"
print(b)
 
 
abc def
[-1, -2.1, -2.0, 'my list', 4]
['changed', -2.1, -2.0, 'my list', 4]
 
 

If you want to create a new object in memory that is a copy of another, then you can index the list. See its visualization here.

 
In [31]:
a = [-1, -2.1, -2.0, 'my list', 4]
c = list(a)   # you can also do c = a[:] or c = copy.copy(a), which basically slices the entire list
a[1] = "two"
print(a)
print(c)
 
 
[-1, 'two', -2.0, 'my list', 4]
[-1, -2.1, -2.0, 'my list', 4]
 
 

The above operation is referred to as a shallow copy. If the original list had any special objects in it (like another list), then the new copy and the old copy will still point to that same object.

There is a deep copy method when you really want everything to be unique in memory. See its visualization here.

 
In [32]:
import copy
a = [-1, -2.1, -2.0, 'my list', 4, [1, 2, 3]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
 
 

When in doubt, use the id() function to figure out where in memory an object lies (you shouldn't worry about the what value of the numbers you get from id mean, but just whether they are the same as those for another object).

 
In [33]:
print(id(a), id(b), id(c), id(d))
print(id(a[-1]), id(b[-1]), id(c[-1]), id(d[-1]))
 
 
2251390964608 2251390964608 2251423072832 2251423084032
2251423084480 2251423084480 2251423084480 2251386293312
 
 

An operator related to the id() function is is. Unlike ==, which compares values, is compares the ids of the objects.

 
In [34]:
a = [1, 2, 3]
b = a
print(a is [1,2,3])
print(a is b)
print(a == [1,2,3])
 
 
False
True
True
 
In [ ]:
 

'Python' 카테고리의 다른 글

6. Recursion vs. Iteration  (1) 2024.03.14
5. Function  (0) 2024.03.14
4. Conditionals and Loops  (0) 2024.03.14
3. Exception Handling  (0) 2024.03.14
1. Data Types  (0) 2024.03.14
'Python' 카테고리의 다른 글
  • 5. Function
  • 4. Conditionals and Loops
  • 3. Exception Handling
  • 1. Data Types
Juson
Juson
  • Juson
    Juson의 데이터 공부
    Juson
  • 전체
    오늘
    어제
    • 분류 전체보기 (95)
      • RAG (2)
      • AI (2)
        • NLP (0)
        • Generative Model (0)
        • Deep Reinforcement Learning (2)
        • LLM (0)
      • Logistic Optimization (0)
      • Machine Learning (37)
        • Linear Regression (2)
        • Logistic Regression (2)
        • Decision Tree (5)
        • Naive Bayes (1)
        • KNN (2)
        • SVM (2)
        • Clustering (4)
        • Dimension Reduction (3)
        • Boosting (6)
        • Abnomaly Detection (2)
        • Recommendation (4)
        • Embedding & NLP (4)
      • Reinforcement Learning (5)
      • Deep Learning (10)
        • Deep learning Bacis Mathema.. (10)
      • Optimization (2)
        • OR Optimization (0)
        • Convex Optimization (0)
        • Integer Optimization (0)
      • SNA 분석 (0)
      • 포트폴리오 최적화 공부 (0)
        • 최적화 기법 (0)
        • 금융 베이스 (0)
      • Finanancial engineering (0)
      • 프로그래머스 데브코스(Boot camp) (15)
        • SQL (9)
        • Python (5)
        • Machine Learning (1)
      • Python (22)
      • Project (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Juson
2. List, Set, Tuple
상단으로

티스토리툴바