Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Python: difference between list and tuple with examples



Lists and tuples both are used to store data in a sequence in Python. Lists are enclosed in square brackets [ ], whereas tuples are enclosed in parentheses ( ).

Here is an example of creating a list in Python:

cv_list = [1, 2, 3, 4, 5]


And here is an example of creating a tuple in Python:


cv_tuple = (1, 2, 3, 4, 5)


To access elements in a list or tuple, you use indexing and slicing. The first element in a list or tuple has an index of 0.

Here is an example of indexing in a list:


print(cv_list[0]) # Output: 1


And here is an example of indexing in a tuple:


print(cv_tuple[0]) # Output: 1


You can also slice a list or tuple to access a range of elements. To slice a list or tuple, you specify the start index and end index separated by a colon :.

Here is an example of slicing a list:


print(cv_list[1:3]) # Output: [2, 3]


And here is an example of slicing a tuple:

print(cv_tuple[1:3]) # Output: (2, 3)


In summary, lists and tuples are both useful data structures in Python, but they have some fundamental differences. Lists are mutable, while tuples are immutable. Lists are used when you need to add, remove, or change elements, while tuples are used when you need to store a collection of elements that won't change. Understanding the differences between these two data structures will help you make the right choice for your program.

Solved : How to zip and unzip files in Python



In this post we will see how to zip and unzip files in python using two modules zipfile and shutil .

You can execute below commands in Jupyter notebook or IDE like Pycharm.

Note: If you are looking for python zip() function check here.

Create a zip using zipfile

First we will use a python module called zipfile to create a zip file containing multiple files.

#import required modules
import zipfile

#Let's create a zip file first by giving it a name
new_zip = zipfile.ZipFile('zip_file.zip','w')
#Add two files which we want to zip
new_zip.write("abc.txt",compress_type=zipfile.ZIP_DEFLATED)
new_zip.write("fileloop.py",compress_type=zipfile.ZIP_DEFLATED)

#Close the zip file
new_zip.close()

So, with the above steps we have created a zip file called zip_file.zip . Now let's try to extract those files in a directory.

Unzip using zipfile 

#import required modules
import zipfile

#First open the file in read mode
unzip_files = zipfile.ZipFile('zip_file.zip','r')

#Now we will unzip and put those files in a directory called extracted_dir
unzip_files.extractall("extracted_dir")

Great! so now our files are extracted in a directory called extracted_dir .


Let's try doing the same using other python module called shutil

Create a zip using shutil

First we will zip a directory.

#import required modules
import shutil
import os

#Give name of your final zipped file. .zip extension will be added automatically.
output_file = 'zip_file_new'

# Give the name of directory which you want to zip.
# If you are in same location as the directory you can simply give it's name or
# else give full path of directory.
# Check your current directory using this command
print(os.getcwd())

#full path of directory to be zipped
zip_dir = 'E:\Software\Python\CloudVedas\extracted_dir'

#Create a zip archive
shutil.make_archive(output_file,'zip',zip_dir)

Note: If your folder name has n in it at the start e.g. new_extracted_dir in that case you will have to escape it using extra "\" since \n will be treated as new line by python so in that case file path should be mentioned as 'E:\Software\Python\CloudVedas\\new_extracted_dir'

So, above we have created a zip file called zip_file_new.zip


Unzip using shutil

Now let's unzip the file zip_file_new.zip we have created earlier .

#import required modules
import shutil

#zipped file full path
zipped_file = 'E:\Software\Python\CloudVedas\zip_file_new.zip'

#full path of directory to where the zipped files will be extracted
extracted_shutil_dir = 'E:\Software\Python\CloudVedas\extracted_dir_new'

#extract the files
shutil.unpack_archive(zipped_file,extracted_shutil_dir,'zip')

Above steps has extracted all the files from our zip and put them in a directory called extracted_dir_new .

In this post we have seen two methods of zipping and unzipping files in python. Do let us know in comments section if you have any query or feedback.

If you want to extract an archive in linux shell you can check our post on how archive or unarchive using tar command.

Solved : How to simply install python pip on windows?

The latest version of python is shipped with pip. But, if you are using older version of python 2(<2.7.9) or python 3(<3.4) and still need pip on windows please follow the instruction below.
If pip is not installed or the path is not set correctly you will get an error like below while invoking it in windows command prompt.
pip install sklearn'pip' is not recognized as an internal or external command,operable program or batch file.
Here are the steps to get pip in your windows box.
  • Download get-pip.py . Copy and paste the contents of the link in a notepad and save it as get-pip.py, remember not in .txt format but .py format.
  • Next install it.
python get-pip.py
  • Find the recently installed pip.exe in your machine. It’s generally in C:\Python27\Scripts or similar folder depending on the python version you installed. You can set the path variable in windows using these instructions.
– Search for “Advanced System Settings” in your windows machine.
– Click on the tab “Advanced”. In it click on Environment Variables.
– In the new window click on System Variables.  Select “Path” and click on “Edit”.
– Click on new and enter C:\Python27\Scripts\ in the space.
– Finally click ok to all windows and re-open command prompt.
  • If you have followed the instructions correctly you will now be able to install packages using pip.
pip install sklearn
That’s all you need to install pip in windows.
Tip:- Some people make mistake of executing pip from Python interpreter and get the below error.

>>> pip install sklearn
File "<stdin>", line 1
pip install sklearn^SyntaxError: invalid syntax
>>>

But, from the above tutorial you now know that pip is installed and executed from command prompt and not from the interpreter.
Hope you find this simple tutorial useful. Let us know in comment section if you face any issue.

Solved: Create virtual environment with python 3 in linux

Once you have installed python 3.6 as described in the last post you can create virtual environment to work with it.
  • First let’s install the package of virtual environment for python 3.
CentOS/RHEL
sudo yum install -y python3-venv
Ubuntu
sudo apt-get install -y python3-venv 
  • Create a directory for you virtual environment and get inside it.
mkdir virtualenvscd virtualenvs
  • Now let’s create our virtual environment.
python3.6 -m venv cloudvedasenv
  • Finally activate the new virtual environment. Notice the new environment name in brackets once you run the source command. That means you are now inside the virtual environment.
[ec2-user@cloudvedas ~]$ source cloudvedasenv/bin/activate
(cloudvedasenv) [ec2-user@cloudvedas ~]$
  • If you want to install a package inside the virtual environment you can use pip .
(cloudvedasenv) [ec2-user@cloudvedas ~]$ pip install zappa requests flask

Solved: Install Python 3 in Linux and set it as default

In this post we will show you how to install python 3 in a Linux box. We have Centos 7 installed in our server.
Check installed python version
Most of the Linux versions by default have python installed. So let's check the current version.
[ec2-user@cloudvedas ~]$ python --version
 Python 2.7.5
[ec2-user@cloudvedas ~]$
As we can see from the above output, currently we have Python 2 installed and we need Python 3 so let's install it.
Install pre-requisites
Before we install python 3 let's first update the yum.
[ec2-user@cloudvedas ~]$ sudo yum -y update
Also, install yum utils.
[ec2-user@cloudvedas ~]$ sudo yum -y install yum-utils
And at the end install the CentOS development tools which will help you build and compile software from source code.
[ec2-user@cloudvedas ~]$ sudo yum -y groupinstall development
Install python 3.6.4
The standard yum repos does not have the latest python release, so we will install IUM (Inline with Upstream Stable) which will have the latest packages.
[ec2-user@cloudvedas ~]$ sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm
Now let's install Python 3.6.
[ec2-user@cloudvedas ~]$ sudo yum -y install python36u
Next we will install pip, which will manage software packages for Python:
[ec2-user@cloudvedas ~]$ sudo yum -y install python36u-pip
Finally, we will install the development packages.
[ec2-user@cloudvedas ~]$ sudo yum -y install python36u-devel
Let' check our  python version
[ec2-user@cloudvedas ~]$ python3.6 -V
Python 3.6.4
[ec2-user@cloudvedas ~]$
Update default python
But if you still run the normal command to check python version it will show the Python 2 version if it was installed by default.
[ec2-user@cloudvedas ~]$ python --version
 Python 2.7.5
 [ec2-user@cloudvedas ~]$
To reflect the new python version by default you create an alias in .bashrc file as described below in the last line of the file.
[ec2-user@cloudvedas ~]$ sudo vi ~/.bashrc

# .bashrc
# Source global definitions
if [ -f /etc/bashrc ]; then . /etc/bashrc fi
# Uncomment the following line if you don't like systemctl's auto-paging feature:
# export SYSTEMD_PAGER=
# User specific aliases and functions
alias python=python3.6
After making the changes save the file. Now, logout and login again, it should show you the new version.
[ec2-user@cloudvedas ~]$ python -V
Python 3.6.4
[ec2-user@cloudvedas ~]$
Check all installed python versions
Do remember that the default python 2 will still remain in the system as lot of system binaries have dependency on it.
To check all the python versions in your box you can check the installed packages as below.
[ec2-user@cloudvedas ~]$ yum list installed | grep -i python
If you want to create virtual environments in python read our next post.