Python Tutorial | Python tuples 3

Slicing

We can access a range of items in a tuple by using the slicing operator – colon “:”.

Example:

n=(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)

Positive index

0

1

2

3

4

5

6

7

c

o

m

p

u

t

e

r

-8

-7

-6

-5

-4

-3

-2

-1

Negative index

n=(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
print(n)
print(n[0:2])
print(n[3:6])
print(n[6:7])
print(n[2:4])
print(n[:4])
print(n[4:])

output:

(‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
(‘c’, ‘o’)
(‘p’, ‘u’, ‘t’)
(‘e’,)
Note: if there is only one element in the output then we will have “,” end the end of tuple output.

(‘m’, ‘p’)
(‘c’, ‘o’, ‘m’, ‘p’)
(‘u’, ‘t’, ‘e’, ‘r’)

n=('c','o','m','p','u','t','e','r')
print(n)
print(n[0:2])
print(n[3:6])
print(n[6:7])
print(n[2:4])
print(n[:4])
print(n[4:])

Output:

('c', 'o', 'm', 'p', 'u', 't', 'e', 'r')
('c', 'o')
('p', 'u', 't')
('e',)
('m', 'p')
('c', 'o', 'm', 'p')
('u', 't', 'e', 'r')
>>> 

Solve:

Example:
n=(‘c’,’a’,’t’,’a’,’l’,’y’,’s’,’t’)
print(n)
print(n[1:5])
print(n[6:7])
print(n[2:6])
print(n[7:])
print(n[3:6])
print(n[:5])
print(n[5:])

Slicing with negative index

n=(‘c’,’a’,’t’,’a’,’l’,’y’,’s’,’t’)

positive index

0

1

2

3

4

5

6

7

c

a

t

a

l

y

s

t

-8

-7

-6

-5

-4

-3

-2

-1

Negative index

n=(‘c’,’a’,’t’,’a’,’l’,’y’,’s’,’t’)
print(n)
#(‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’)

print(n[-5:-3])
#(‘a’, ‘l’)

print(n[-5:-2])
#(‘a’, ‘l’, ‘y’)

print(n[2:6])
#(‘t’, ‘a’, ‘l’, ‘y’)

print(n[-7:])
#(‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’)

print(n[-6:-4])
#(‘t’, ‘a’)

print(n[:-5])
#(‘c’, ‘a’, ‘t’)

print(n[-5:])
#(‘a’, ‘l’, ‘y’, ‘s’, ‘t’)

Solve:

n=(1,2,3,4,5,6,7,8,9,10)
print(n)
print(n[0:2])
print(n[3:6])
print(n[6:7])
print(n[2:4])
print(n[:4])
print(n[4:])

 

Solve:

n=(1,2,3,4,5,6,7,8,9,10)
print(n)
print(n[0:-2])
print(n[-6:-3])
print(n[-7:-5])
print(n[-4:-2])
print(n[:-4])
print(n[-4:])

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling

Visitor Counter

0056682