Python [Post 07] | Tuple

A tuple is a collection which is ordered and unchangeable. It is similar to list, but a tuple is immutable unlike lists which are mutable.

It is created by placing items inside a parentheses (), separated by comma. Parentheses is optional.

# Creating Tuple

empty_tuple = ()
my_tup1 = 'N','S','E','W'
my_tup2 = ('North','South','East','West')

print(type(empty_tuple))
print(my_tup1)
print(my_tup2)

<class ‘tuple’>
(‘N’, ‘S’, ‘E’, ‘W’)
(‘North’, ‘South’, ‘East’, ‘West’)

Other way to create tuple by using the tuple() constructor. See below example.

my_tup3 = tuple((1,'South',5.5,('A','B','C'),[0,1,2]))

print(my_tup3)
print(type(my_tup3))

(1, ‘South’, 5.5, (‘A’, ‘B’, ‘C’), [0, 1, 2])
<class ‘tuple’>

# Creating a tuple having single value

my_tup4 = (4)
print(type(my_tup4)) # But the result is showing int, i.e. this is not a tuple

<class ‘int’>

To create a tuple having single value, Just include comma at last.

my_tup4 = (4,)
print(type(my_tup4)) # Now its a tuple

<class ‘tuple’>

Some Built-in Python Functions

my_tup5 = 1,2.5,3,4

print(type(my_tup5)) # Type
print(len(my_tup5)) # len Function - Gives the total length of the tuple.
print(max(my_tup5)) # max Function - Returns element from the tuple with maximum value.
print(min(my_tup5)) # min Function - Returns element from the tuple with minimum value.

<class ‘tuple’>
4
4
1

### Accessing Tuple Values – Indexing & Slicing

Use the index operator [] to access an item in a tuple. We can use a : to perform slicing which extracts chunk of more than one element as per input. In slicing last index is not included.

sides = 'East','West','North','South'
# Fetch the first element of list sides

print(sides[0])

East

# Fetch the last element of list sides

print(sides[-1])

South

# fetch elements start from index 1st till last

print(sides[1:])

(‘West’, ‘North’, ‘South’)

# fetch elements upto 2nd index, but 2nd is not included

print(sides [:2])

(‘East’, ‘West’)

# fetch element from 1st index to 3rd index

print(sides [1:3])

(‘West’, ‘North’)

# fetching values in case of nested tuple

my_tup = tuple((1,'South',5.5,('A','B','C'),[0,1,2]))

print(my_tup[3][0])
print(my_tup[3][2])

A
C

### Updating Tuples

Python Tuple is immutable i.e. the elements inside a tuple cannot be changed!

sides = ('East','West','North','South')

# Let's try to change the elements of lists sides

sides[0]= 1

TypeError Traceback (most recent call last)
<ipython-input-14-b1dd30231e62> in <module>()
3 # Let’s try to change the elements of lists sides
4
—-> 5 sides[0]= 1
TypeError: ‘tuple’ object does not support item assignment

### Deleting Tuples

Individual element in tuple cannot be removed. Entire tuple can be removed by using del statement.

# Removing tuple completely

del sides
sides # This will raise exception, as sides tuple removed

NameError Traceback (most recent call last)
<ipython-input-16-7623a01b7793> in <module>()
—-> 1 sides # This will raise exception, as sides tuple removed
NameError: name ‘sides’ is not defined

### Concatenation & Repetition of Tuples

sides = ('East','West','North','South')
modesides = ('North-East','North-East','South-East','South-West')

print(sides)
print(modesides)

(‘East’, ‘West’, ‘North’, ‘South’)
(‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

# Concatenation

sides = sides + modesides
print(sides)

(‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

# Repetition

sides = sides * 2
print(sides)

(‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’, ‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

### Tuple Method

Python includes following tuple methods.

Index() :

Returns the index of the first matched item.

sides = 'EAST','West','North','East','South','East'

print(sides.index('East'))
print(sides.index('West'))

3
1

Count():

Returns the count of number of items passed as an argument.

print(sides.count('East'))

2


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in
Github Code Link

Advertisements

Python [Post 04] | Strings

Folks,

In this blog post we will explore Python strings & string methods. Python strings are sequences of characters. Here are some examples of strings.

# Printing String

print('This is a string!') # Enclosed using single quote

print("This is also a string!") # Enclosed using double quote

print("""This is also a string,
also having next line.""") # Enclosed using triple quote. Multiple lines are generally put in triple quotes.

print("It's ok!") # Use double quote to enclose the string, if string is having single quote
print('P') # Python treat this single character also as string

This is a string!
This is also a string!
This is also a string,
also having next line.
It’s ok!
P

### String Indexing

Python strings are sequences of individual characters. We can access characters in strings by index. In Python index starts from 0, also if you want to start from the end, instead of the beginning then use a negative index.

Indexing Example: String x = ‘Python’

+ve Index 0 1 2 3 4 5
+ve Index 0 -5 -4 -3 -2 -1

# String Variable
x = 'Python'
x[0] # Fetch the first character of string x

‘P’

x[1] # Fetch the second character of string x

‘y’

x[-1] # Fetch the last character of string x

‘n’

Python strings are immutable. i.e. Once string is created, the elements within it can not be changed or replaced.

# Let's try to change the first letter to 'J' of string x
x[0] = 'J'

TypeError Traceback (most recent call last)

<ipython-input-6-5b400f918714> in <module>()
1 # Let’s try to change the first letter to ‘J’ of string x
—-> 2 x[0] = ‘J’

TypeError: ‘str’ object does not support item assignment

 

You can “update” an existing string by (re)assigning a variable to another string.

x = 'J' + x[1:]
print(x)

Jython

### Slicing Python String

We can use a : to perform slicing which extracts chunk of more than one character as per input. In slicing last index is not included.

String x = ‘Python’

+ve Index 0 1 2 3 4 5

+ve Index 0 -5 -4 -3 -2 -1

For Example:

# String Variable
x = 'Python'
x[0:2] # fetch the first 2 character of string x. x[0:2] is same as x[:2]

‘Py’

x[:3] # fetch the first 3 character of string x

‘Pyt’

x[2:5] # fetch character from 2nd index to 3rd index

‘tho’

x[2:] # fetch charcters start from index 2nd till last

‘thon’

x[:3] # fetch charcters upto 3rd index, but 3rd is not included

‘Pyt’

x[-5:-1] # Negative Index also works in slicing

‘ytho’

x[::] # fetch complete string

‘Python’

Skipping Characters using third parameter

x = 'Python'
x[::1] # Default is 1

‘Python’

x[::2] # Skip every 2nd character

‘Pto’

x[0:5:2] # Skip every 2nd character

‘Pto’

x[::-1] # Reverse String

‘nohtyP’

### String Methods Examples

Python String provides so many methods to do the string manipulations. See below examples.

# Split - Splits string as per provided delimiter ( default space) and returns list of substrings;

x = 'Python is fully-functional programming language that can do almost anything'
print(x.split())

[‘Python’, ‘is’, ‘fully-functional’, ‘programming’, ‘language’, ‘that’, ‘can’, ‘do’, ‘almost’, ‘anything’]

x = 'A,B,C,D,E,F'
print(x.split(',')) # Comma as delimeter

[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’]

# Upper & Lower Case

x = 'Python'
print(x.upper())
print(x.lower())

PYTHON
python

# Checking String whether contains only alpha or numeric

x = 'Python3'
print(x.isalnum())
print(x.isalpha())
print(x.isnumeric())
len(x)

True
False
False
7

Lstrip, RStrip & Strip Method – For removing white spaces

# lstrip - Remove white space from left

x = ' Python3 '
x.lstrip()

‘Python3 ‘

# rstrip - Remove white space from left

x = ' Python3 '
x.rstrip()

‘ Python3’

# rstrip - Remove white space from left & right

x = ' Python3 '
x.strip()

‘Python3’

.format() String Method

Insert objects dynamically in the string using assigment keywords or index. It can also persorm alignment, padding & precision of floating point numbers.

import datetime
d = str(datetime.datetime.now())
# Example 1 -

x = "Today's date & time is {}"

x.format(d)

“Today’s date & time is 2018-07-08 02:04:47.893499”

# Example 2

x = "Today's date & time is %s" %datetime.datetime.now()

print(x)

Today’s date & time is 2018-07-08 02:04:49.885035

# Example 3

print('a {f} in need is a {f} indeed'.format(f='friend'))
print('a {0} in need is a {0} indeed'.format('friend'))

a friend in need is a friend indeed
a friend in need is a friend indeed

# String Formatting Operator - %
# Oldest method involves placeholders using the modulo % character. %s for string, %c is for character, %i integer, %f float etc

print('a %s in need is a %s indeed' %('friend','friend'))

x = "Today's date & time is %s" %datetime.datetime.now()
print(x)

x = "My name is %s, my age is %i & my height is %f" % ('John', 21, 150.56)
print(x)

a friend in need is a friend indeed
Today’s date & time is 2018-07-08 02:04:50.634701
My name is John, my age is 21 & my height is 150.560000

Precision of Float with .format() Method

You can add precision for float point numbers in string. See below example.

x = “My height is %5.1f” % (150.5678)

  • .1f stands for how many numbers to show past the decimal point.
  • 5 would be the minimum number of characters the string should contain. Padded with whitespace if the entire number does not have this many digits.
x = "My height is %5.1f" % (150.5678)
print(x)

My height is 150.6

x = "My height is %15.2f" % (150.5678)
print(x)

My height is 150.57

Padding & Alignment with .format() Method

# Padding

print('{0:5} | {1:3}'.format('FName', 'Age'))
print('{0:5} | {1:3}'.format('A', 14))
print('{0:5} | {1:3}'.format('B', 12))

FName | Age
A | 14
B | 12

By default, .format() aligns text to the left, numbers to the right.
Pass an optional <,^, or > to set a left, center or right alignment as per requirement.

# Alignment

print('{0:^5} | {1:^3}'.format('FName', 'Age'))
print('{0:^5} | {1:^3}'.format('A', 14))
print('{0:^5} | {1:^3}'.format('B', 12))

FName | Age
A | 14
B | 12

print('{0:-^10} | {1:-^10}'.format('FName', 'Age'))

–FName— | —Age—-

There are many more string methods eg. count, find, decode, encode, index etc.


Thanks!

Happy Learning! Your feedback would be appreciated!
shobhitsingh.in

[GitHub Code]