Size of list and string
<p>I am trying to fetch the size of list in bytes and also size of string in bytes.</p>

<p>If we see the output below for the code, size of list is shown as <code>52 bytes</code>, where as when I join the list and check the size, output is <code>35 bytes</code>. At last I tried to get size of string <code>"Iamtestingsize"</code> the output was again <code>35 bytes</code>. So, size of string after "join" and also size of string  "Iamtestingsize" is same.</p>

<p>I have 2 questions here:</p>

<p>1) why is the size of list showing a different output ? also, please let me know if you have any idea on how to fetch the size of contents of list ?</p>

<p>2) I thought, 1 byte == 1 character and I was expecting size of strings msgstr and string will show as 14 bytes instead of 35. Please let me know if am missing anything here ?</p>

<p>3) when I perform len() on list and strings, for msgstr and string - 14 was returned whereas length of list returned 4 which is as I expected. </p>

<pre><code>import sys

list = ['I', 'am', 'testing', 'size']
print sys.getsizeof(list)
msgstr = "".join(list)
print "size of msgstr is " + str(sys.getsizeof(msgstr))
print msgstr
string = "Iamtestingsize"
print "size of str is " + str(sys.getsizeof(string))
print len(list)
print len(msgstr)
print len(string)

Output:

52
size of msgstr is 35
Iamtestingsize
size of str is 35
4
14
14
</code></pre>

<p>Note: I am using python 2.7</p>

<ol>
<li><p>A list (any list) data structure requires additional maintenance overhead to keep elements inside it. This overhead is reflected in the difference of the results of <code>getsizeof</code>.</p></li>
<li><p>Python strings are a <a href="https://docs.python.org/2.7/library/stdtypes.html#typesseq" rel="nofollow">text sequence type - str</a>, and not C strings or anything alike. Same as Python lists, there is associated metadata involved, beyond the contents of the string alone:</p></li>
</ol>

<hr>

<pre><code>Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; import sys
&gt;&gt;&gt; sys.getsizeof(b'asd')
40
&gt;&gt;&gt; sys.getsizeof('asd')
40
&gt;&gt;&gt; sys.getsizeof(u'asd')
56
</code></pre>

<hr>

<ol start="3">
<li>The length of a string is, intuitively, defined as the number of characters in it.</li>
</ol>

python python-2.7