Best post on mutable list, list operations python – 2

List datatype and List operations

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.

List datatype is Mutable

As we know mutable data type indicates datatypes which are editable or changeable in same variable name.

We can modify existing list and so lists are mutable datatype.

We can add new values at any location in existing or original list.

Lists are Mutable - Justified

We can change or assign any new value using [ ] operator in existing list.

Example:

>>> itv=[1,2,3,4,5,6]
>>> itv[5]='a'
>>> itv
[1, 2, 3, 4, 5, 'a']
>>> itv[6]='added'
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
itv[6]='added'
IndexError: list assignment index out of range
>>>

This IndexError: list assignment index out of range proves that we cannot add new value on index position out of existing list .

As we receive above message, it becomes that list datatype can update original value but only within given index range and lists are mutable.

List comprehension

The list comprehension is used to hold multiple for and if statements and give out the result using single line.

List comprehension consist of output expression followed by for statement , then zero or more for and if statements as per requirement.

The result of list comprehension is always a list consisting of values or tuples of value.

Example

>>> [x**2 for x in range(6) if x%2==0]
[0, 4, 16]
>>> [x*2 for x in range(6) if x%2!=0]
[2, 6, 10]
>>> [x+y for x in range(6) for y in [1,3,5,7,9] if x!=y]
[1, 3, 5, 7, 9, 4, 6, 8, 10, 3, 5, 7, 9, 11, 4, 8, 10, 12, 5, 7, 9, 11, 13, 6, 8, 12, 14]
#Use list comprehension to get a list of square root of all odd numbers between 1 to 20 in python

>>>
K=[x**0.5 for x in range(21) if x%2!=0]
>>> K
[1.0, 1.7320508075688772, 2.23606797749979, 2.6457513110645907, 3.0, 3.3166247903554, 3.605551275463989, 3.872983346207417, 4.123105625617661, 4.358898943540674]

How to search in a list?

We can search an item or element from a list.

Following example will help us for better understanding :

Example:

#function definition
def search_a_list(L,ele):
for i in range(len(L)):
if L[i]==ele:
print("match found")
break
else:
print("match not found")
#function call
search_a_list([1,2,3,4,5,6],10)
search_a_list([1,2,3,4,5,6],1)

Output:

>>> 
match not found
match found
>>>

Looping and counting on list

We can use loops for counting or traversing a lists.

Following example will help us for better understanding :

Example:

#Script to calculate number of times i exists in ['i', 't', 'v', 'o', 'y', 'a', 'g', 'e', 'r', 's', '.', 'i', 'n']
itv=['i', 't', 'v', 'o', 'y', 'a', 'g', 'e', 'r', 's', '.', 'i', 'n']
counter = 0
for letter in itv:
    if letter =='i':
        counter+=1
print("Count of i in given list is ", counter)

 

Output:

>>> 
Count of i in given list is 2

This example indicates that by using loops and counter we can easily find count of elements present in particular list.

List Operations

Python supports various list operations which helps in performing tasks easily.

Various list operations include concatenation, repetition, in operator, not in operator, range and slice operators.

Some of the list operations are explained below:

 

List operations in python

  • + : Concatenation operator
    • This operator is used to join or merge two lists together, i.e. values to the either side of + operator will be merged or concatenated.
    • >>> List1=[1,2,3,'p','o','s','t']
      >>> List2=[5,6,7,8,'a','b','c']
      >>> List1 + List2
      [1, 2, 3, 'p', 'o', 's', 't', 5, 6, 7, 8, 'a', 'b', 'c']
  • * : Repetition operator
    • This operator creates new list by creating copies of same list. 
    • This operator here does not multiply number with list but it creates copies of list as per specified number.
    • >>> List3=[5.5,8,6.6,2]
      >>> List3 * 2
      [5.5, 8, 6.6, 2, 5.5, 8, 6.6, 2]
      >>>
  • [] : Slice operator
    • This operator is used to get a character from the given list by specifying the index position in [].
    • >>> List4=[9,8,7,6,5,4,3,2,1]
      >>> List4[1]
      8
      >>> List4[8]
      1
      >>> List4[5]
      4
      >>>
  • [:]  : Range Slice operator
    • This operator is used to slice a list by specifying start and end position and also an optional parameter of step value.
    • >>> List4=[9,8,7,6,5,4,3,2,1]
      >>> List4[4:6]
      [5, 4]
      >>> List4[4:4]
      []
      >>> List4[4:2:-2]
      [5]
      >>> List4[4:8:2]
      [5, 3]
  • in : Membership operator (in)
    • This operator will return True is character is present in given list and False otherwise.
    • >>> List4=[9,8,7,6,5,4,3,2,1]
      >>> 5 in List4
      True
      >>> 15 in List4
      False
  • not in : Membership operator(not in)
    • This operator will return True is character is not present in given list and False otherwise.
    • >>> List4=[9,8,7,6,5,4,3,2,1]
      >>> 5 not in List4
      False
      >>> 15 not in List4
      True

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