Web
Analytics
List in Python with example - Tutorial

For Consultation : +91 9887575540

Stay Connected :

What is List:

  • a built-in data structure available in Python
  • a list of comma-separated values (items) between square brackets.
  • It can contain heterogeneous values such as integers, floats, strings, tuples, lists, and dictionaries.
  • Python lists are mutable; yes, they can change
  • a = [ 1, 342, 2233423, ‘India’, ‘Fedora’]
  • It works as a sequence
  • Ex : a[0] result=>1

How to create a list:

  • Creating a list

Syntax: <variable_name>= []

Example :  List1 = []

Creating a list with value

Trainers= [‘yogesh’, ‘sharma’, ‘vikas’]

Slicing the list

<list_name>[start : stop : step]

Trainers[1:3]

Trainers[:4]

list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13]

Operation: list1[1:13:3]

Result: [2, 5, 8, 11]

Deleting values from a list

  • By using the del keyword, you can delete a value or a slice of list from the list.

C_W_team = [‘hulk’, ‘iron-man’, ‘Captain-America’, ‘Thor’,”Vision”]

del C_W_team[0]

C_W_team [‘iron-man’, ‘Captain-America’, ‘Thor’, ‘Vision‘]

Unpacking List Values

  • a,b = [10,20]
  • You can assign a list value to variables by using the assignment operator.

List Operations:

  • Updating the list:Lists are mutable, so the values of a list can be updated.

Syntax : ListName[index]=new_value

  • Addition of Python lists:You can add two lists by using the + operator

   Syntax : List3 = List1+List2

  • Multiplication of lists :By using the * operator, you can perform multiplication of Python lists

  syntax: List2 = List1*2

  • in operator:You can use the in operator on list with the if statement
  • Syntax: if ‘value’ in list:
  • statement-1

List Functions:

  • len() :The len() function returns the number of elements or values in the list
  • max () :The max (list) function returns the element of the list with the maximum value.
  • min () : The min () function returns an element from the Python list with the minimum value.
  • sorted () : return list with sorted item.

List Methods:

  • append () : Syntax: list.append ()

The method adds a value at the end of the list.

  • extend (): list1.extend (seq) .
  • Count():The count () method is used to find the occurrence of an item in a list.
  • index () :The index () method is used to find the index of a particular item in a list.
  • insert():Insert an item into list

–Syntax: list1.insert (index1, item)

  • remove(): Remove an item from list.

list.remove(item)

  • Pop(): The pop () method removes and returns the last item from the list.

list.pop()

 

Select your currency