Python Keywords, Identifiers and Statements 13

Python List

List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items/elements in a list do not need to be of the same type.
Declaring a list is straight forward. Items separated by commas are enclosed within brackets [ ].

>>> a = [1, 2.2, ‘python’]

We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts form 0 in Python.

Example:1:

#testing list
a=[10,20,30,40,50,60,70,80,90,100]
#to display all list values
print(a)
#to print 2nd element counting starts from 0
print("2nd element ",a[1])

print("a[0] element ",a[0])
print("a[1] element ",a[1])
print("a[2] element ",a[2])
print("a[3] element ",a[3])
print("a[4] element ",a[4])

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
2nd element  20
a[0] element  10
a[1] element  20
a[2] element  30
a[3] element  40
a[4] element  50
>>> 

example:2:

a=[10,20,30,40,50,60,70,80,90,100]
#to display all list values
print(a)
print(a[1:3]) 
print(a[0:3]) 
print(a[:3]) 
print(a[2:5])
print(a[5:])
print(a[4:7])

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[20, 30]
[10, 20, 30]
[10, 20, 30]
[30, 40, 50]
[60, 70, 80, 90, 100]
[50, 60, 70]
>>> 

Example:3:

n=["amit","sumit","rohit","kishan","kapil","vinay","mohit","gopal"]
#to display all list values
print(n)
print(n[1:3]) 
print(n[0:3]) 
print(n[:3]) 
print(n[2:5])
print(n[5:])
print(n[4:7])

Output:

['amit', 'sumit', 'rohit', 'kishan', 'kapil', 'vinay', 'mohit', 'gopal']
['sumit', 'rohit']
['amit', 'sumit', 'rohit']
['amit', 'sumit', 'rohit']
['rohit', 'kishan', 'kapil']
['vinay', 'mohit', 'gopal']
['kapil', 'vinay', 'mohit']
>>> 

Python Tuple

Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically.
It is defined within parentheses () where items are separated by commas.
>>> t = (1,2,3,4,5,’program’)
We can use the slicing operator [] to extract items but we cannot change its value.

Example:1

a=(10,20,30,40,50,60,70,80,90,100)
#to display all tuple values
print(a)
#to print 2nd element counting starts from 0
print("2nd element ",a[1])

print("a[0] element ",a[0])
print("a[1] element ",a[1])
print("a[2] element ",a[2])
print("a[3] element ",a[3])
print("a[4] element ",a[4])

Output:

(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
2nd element  20
a[0] element  10
a[1] element  20
a[2] element  30
a[3] element  40
a[4] element  50
>>> 

Example:2

a=(10,20,30,40,50,60,70,80,90,100)
#to display all tuples values
print(a)
print(a[1:3]) 
print(a[0:3]) 
print(a[:3]) 
print(a[2:5])
print(a[5:])
print(a[4:7])

Output:

(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
(20, 30)
(10, 20, 30)
(10, 20, 30)
(30, 40, 50)
(60, 70, 80, 90, 100)
(50, 60, 70)
>>> 

Visitor Counter

0056684