Best post on list datatype in python – 1

List Datatype in Python

Python supports many simple and compound datatypes.

Few data types like list, dictionary are mutable and others like string datatype, tuple are immutable.

Mutable datatypes means changes can be done and are reflected in same variable.

Immutable datatypes means changes can be done but not in same variable.

List is a container for holding items or elements of same or different datatypes.

An empty list represents zero character or we can call it as null list.

A list datatype can be defined with use of opening and closing square brackets [ ].

The elements present in the list are separated by comma.

Initializing a List

We can initialize a list as empty list using [] or with values.

This values can be of different datatypes.

You can also initialize two or more lists in single line.

Example

>>> itv=[] #empty list
>>> itv1=[1,2.3,'python']
>>> itv
[]
>>> itv1
[1, 2.3, 'python']
>>> itv2=[1,2,3,4,5,6]
>>> itv2
[1, 2, 3, 4, 5, 6]
>>> itv3=['i','t','v','o','y','a','g','e','r','s']
>>> itv3
['i', 't', 'v', 'o', 'y', 'a', 'g', 'e', 'r', 's']
>>> F,O,G=[1,2],['h','i'],[1,5.3,'p']
>>> F
[1, 2]
>>> O
['h', 'i']
>>> G
[1, 5.3, 'p']

 

Accessing a list

A list can be accessed using square brackets [].

Example

>>> itv=['i','t','v','o','y','a','g','e','r','s']
>>> itv[5]
'a'
>>> itv[9]
's'
>>> print("First five elements", itv[0:6])
First five elements ['i', 't', 'v', 'o', 'y', 'a']
>>> print("last five elements in reverse", itv[10:4:-1])
last five elements in reverse ['s', 'r', 'e', 'g', 'a']
>>>

>>> itv[11]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
itv[11]
IndexError: list index out of range

 

Above example consist of a list having 10 characters and index position starting from 0 till 9. To access a string we need to pass index value inside square brackets to retrieve character located on that index. As last index number is 9 we get and IndexError if we pass an index greater than 9. So first letter ‘i’ is at position 0, second letter ‘t’ is at position 1 and so on..

Example:

>>> itv=['i','t','v','o','y','a','g','e','r','s']
>>> itv[2.5]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
itv[2.5]
TypeError: list indices must be integers, not float

From above example it is clear that we cannot use a float value as index. An index should always be an integer and last value of index will always be n-1 if total length is n.

len function or len()

Python provides a built-in function called as len() to calculate number of characters in a list or simply we can say length of a list.

Example:

>>> itv=[]
>>> len(itv)
0
>>> itv1=[1,2.3,'python']
>>> len(itv1)
3
>>> itv2=[1,2,3,4,5,6]
>>> len(itv2)
6
>>> itv3=['i','t','v','o','y','a','g','e','r','s']
>>> len(itv3)
10

 

If we wish to get last letter of the list we might script it as follows:

>>> itv=['i','t','v','o','y','a','g','e','r','s']
>>> h=len(itv)
>>> last=itv[h]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
last=itv[h]
IndexError: string index out of range
>>> 

This raises an IndexError. So to over come this we can modify code using following script:

>>> itv=['i','t','v','o','y','a','g','e','r','s']
>>> h=len(itv)
>>> last=itv[h-1]
>>> last
's'
>>>

Negative Indexing

We can use negative indexing for list datatype which will help us to count backward from the end of the list.

If we use itv[-1] it will give output as ‘s’.

>>> itv=['i','t','v','o','y','a','g','e','r','s']
>>> itv[-1]
's'
>>> itv[-8]
'v'
>>> itv[-10]
'i'
>>> itv[-11]
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
itv[-11]
IndexError: list index out of range

In negative indices, index begins with -1 and not 0 so last value of indexing will be -10 in our example and not -9.

Traversing list using for loop

Traversing is a process of moving in an iterable and locating values from index position.

In this case our iterable is of type list and loop used is for loop.

>>> itv=['i','t','v','o','y','a','g','e','r','s']
>>> for i in itv:
	print("Letter is", i * 2)
 

Output:

Letter is ii
Letter is tt
Letter is vv
Letter is oo
Letter is yy
Letter is aa
Letter is gg
Letter is ee
Letter is rr
Letter is ss

List slicing

A list datatype can be sliced using [ : ] .

Syntax:

[start : end : step]

This provide start and end value.

Sometimes a step value is also mentioned after end value using colon separation.

In below example we will see multiple outputs or multiple ways to slice a list datatype.

 

Example:

#List slicing
demo_list = ['i','t','v','o','y','a','g','e','r','s','.','i','n']
print('demo_list[0:5]',demo_list[0:5])
print('demo_list[9:12]',demo_list[9:12])
print('demo_list[5:12]',demo_list[5:12])
print('demo_list[:3]',demo_list[:3])
print('demo_list[3:]',demo_list[3:])
print('demo_list[3:3]',demo_list[3:3])
print('demo_list[:]',demo_list[:])
print('demo_list[0]',demo_list[0])
print('demo_list[10]',demo_list[10])
print('demo_list[5]',demo_list[5])
print('demo_list[5:14:2]',demo_list[5:14:2])
print('demo_list[5::2]',demo_list[5::2])
print('demo_list[:14:2]',demo_list[:14:2])
print('demo_list[5:1:-2]',demo_list[5:1:-2])
print('demo_list[5:1:-1]',demo_list[5:1:-1])
print('demo_list[::]',demo_list[::])

 

Output:

slicing of list datatype(itvoyagers.in)
slicing of list datatype(itvoyagers.in)

Other python related post

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon…….

Other advance python related post

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in ‘re’ module(Part I)- Match vs Search
Functions in ‘re’ module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
New posts coming soon…….
We are aiming to explain all concepts of Python in easiest terms as possible.
ITVoyagers-logo
ITVoyagers
Author

Leave a Comment