Difference between list, set and tuples in Python and more such comparisons

In this article we will see key differences between commonly used terms in python. For example difference between tuple and list, difference between range and xrange and so on.


List and Tuples:


List:
- are mutable i.e. we can add, extend or update a list.
- generally are homogeneous data structures.


>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Tuples:
- are immutable i.e. we can not update a tuple.
- generally are heterogeneous data structure.
- is a sequence where position have semantic value.
- are more like records, collection of fixed number of fields.

>>> import time
>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=25, tm_hour=21, tm_min=52, tm_sec=24, tm_wday=0, tm_yday=268, tm_isdst=0)
 

Set:

- is just like mathematical set.
- is unordered.
- is mutable.
- doesn't contain duplicate values.

rana@Brahma: ~$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = [1,2,5,2,3]
>>> a = set(mylist)
>>> a
{1, 2, 3, 5}



range() and xrange():


range():
- In python2 range() function returns a list of integers.

rana@Brahma: ~$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 - In python3 range() do whatever xrange use to do in python2 i.e. returns the generator object that can be used to display numbers only by looping. Only particular range is displayed on demand and hence called "lazy evaluation".

rana@Brahma: ~$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = xrange(10)
>>> a
xrange(10)
>>> [i for i in xrange(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

xrange():
- There is no xrange() function in python3. We already know what xrange() use to do in python2.

>>> a = xrange(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'xrange' is not defined

 - Since we are moving towards python3, we will not have any further discussion about it. If you are really interested visit this link.


raw_input() and input():


input():
- In python2, input() tries to run the user input as a valid python expression.

rana@Brahma: ~$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> input()
2^3
1
>>> input(2**3)
8

 - In python3, return the user input as string.


raw_input():
- In python2, return the user input as string.
- Doesn't exists in python3. To simulate the raw_input() in python3, use eval(input()).



Shallow and deep copy:


Before comparing shallow and deep copy, we must know that normal assignment is just pointing new variable to existing object.

rana@Brahma: ~$ python3
Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:09:58) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2]
>>> b = a
>>> print(id(a) == id(b))
True


Comparison of shallow copy and deep copy is relevant for compound objects i.e. where objects contains another objects.


Shallow copy: Shallow copy creates a new object and then use the reference to refer the inner objects.

>>> a = [[1,2],[3,4]]
>>> b = a.copy()
>>> print(id(a) == id(b))
False
>>> print(id(a[0]) == id(b[0]))
True


Deep copy: deep copy create a new object and recursively copy the inner objects too.

>>> from copy import deepcopy
>>> a = [[1,2],[3,4]]
>>> b = deepcopy(a)
>>> print(id(a) == id(b))
False
>>> print(id(a[0]) == id(b[0]))
False

id() function return the identity of the location of the object in memory.

>>> print(id(a))
139724773442120


Unicode and str:

Here is a nicely written article explaining the difference between str, unicode and byte.

unicode str byte
Python 2 unicode characters raw 8 bit values n/a
Python 3 n/a unicode characters raw 8 bit values


*args and **kwargs:

*args:
- is used to pass the variable length list of non-keyworded arguments to function.

*kwargs:
- is used to pass the variable length list of keyworded arguments to a function.

Always pass arguments in this order : formal arguments then non-keyworded argument list and then keyworded arguments list.    




Print statement in Python vs other programming languages

In this article we are simply presenting the code blocks required in different programming laguages to print 'pythoncircle.com' on terminal. This shows the amount of code you need to write to print a simple string. 


C:

#include <stdio.h>
int main()
{
  printf("pythoncircle.com");
  return 0;
}


C++:

#include <iostream>
using namespace std;

int main() 
{
    cout << "pythoncircle.com";
    return 0;
}


PHP:

<?php
  echo "pythoncircle.com";
?>


C#:

using System;
namespace HelloWorld
{
    class Hello 
    {
        static void Main() 
        {
            Console.WriteLine("pythoncircle.com");
            Console.ReadKey();
        }
    }
}


JAVA:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("pythoncircle.com");
    }
}

And now

Python:


print("pythoncircle.com")


That is all you need in python to print a statement. This shows the simplicity of Python. 



Solving Django Error: TemplateDoesNotExist at /app_name/


TemplateDoesNotExist at /app_name/

If you are facing above template error, there is a high possibility that at-least one of the below listed point applies to you.



1. Wrong template name:

Make sure when rendering the template, you are using right name of template. 

return render(request, 'app_name/tools.html', data)

Check if template name is actually tools or it is tool?



2. Wrong app name:

In the above render statement, confirm if the appname used is correct or not.

return render(request, 'app_name/tools.html', data)



3. Installed Apps:

Please confirm if your app is listed in installed apps in settings.py file.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'your-app-here',
]



4. Template Directory Structure:

Make sure your templates are places inside a directory with same name as your app's name which in itself is inside templates directory. Confused? 

So your templates directory structure should be as below.

app_name
|
|-templates
|    |-app_name
|    |    |-tools.html



5. Where is Django looking for templates:

Confirm if Django is looking for templates in app directories. For this you need to see templates setting in settings.py file. Check if APP_DIR is set to True. If this is set to False, Django won't look for templates in app directories.

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]



6. Project level templates:

If you are using something like below in your project's urls.py file

urlpatterns += [
path(r'robots.txt/', TemplateView.as_view(template_name="project_name/robots.txt", content_type='text/plain')),
]


It could be any file instead of robots.txt, then make sure there is templates directory in root directory of project. This template directory is outside of every app. Directory structure would be as below.

|-project_name
|    |-templates
|    |    |-project_name
|    |    |    |-your-template-here


These template files are project level template files.

Also add 'DIRS': [os.path.join(BASE_DIR, 'templates')],  in TEMPLATES tuple in settings.py file. BASE_DIR is defined in settings.py file at the top. If not define as below.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


If you are still unable to resolve the error, feel free to comment or contact us or connect on facebook page.

Host your Django project for free.



SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.


Recent Posts:






© pythoncircle.com 2018-2019
Contact Us: code108labs [at] gmail.com
Address: 3747 Smithfield Avenue, Houston, Texas