List

  • List items are ordered, changeable, and allow duplicate values.
  • It is created by placing all the items (python objects) inside square brackets [], separated by commas.
  • Python objects may be of different types (integer, float, string etc.)
  • Lists in Python can be created by just placing the sequence inside the square brackets[].
  • colors = [‘red’, ‘blue’, ‘green’]

To ensure List are ordered you can check below statements

a = [1,2,"Peter",4.50,"Ricky",5,6]  

b = [1,2,5,"Peter",4.50,"Ricky",6]  

a ==b  

A list with a single object is sometimes referred to as a singleton list

The list() Constructor

  • It is also possible to use the list() constructor when creating a new list.
  • x= list((“apple”, “banana”, “cherry”)) # note the double round-brackets

Type casting-List

X = ‘hello’

Y = list(x)

List(Iterable_object)

Read or access

  • List items are indexed and you can access them by referring to the index number that nay be positive or negative.
  • Positive index start with zero ( First Element)
  • Negative index start with -1 ( Last Element)
  • You can also use slicing to select multiple element in the list. [:] and [start:stop:step]

Update

refer the index number

x= ["apple", 56.32, 23]
x[0] = "blackcurrant“

#you can also mention range of index

x[1:3] = [99.99, "watermelon"]

In case you specify more elements during update then it will insert the remaining value

x[1:2] = [99.99, "watermelon"]

In case you specify less items than you replace , then you will lose particular index value

Insert New Elements

  • Append
  • Concatenation
  • Insert
  • Extend

Append

It will add an item to the end of the list

x= [“Hello", "banana", 23]


x.append("orange")

Concatenation

Syntax

List A

List B

List C = List A + List B

Insert

The insert() method inserts an item at the specified index

Syntax

X.insert(index,value)

x = [1,2,3,4,5]

x.insert(0,55) ----> [55,1,2,3,4,5]

Extend

To append elements from another listto the current list, use the extend() method

Syntax

x.extend(y)

#you can extend any iterable object (tuples, sets, dictionaries etc.).

x = [1,2,3,4,5]

y = [10,20,30]

x.extend(y) ------> [1,2,3,4,5,10,20,30]

Remove

  • Del
  • Pop
  • Remove
  • clear

Del

del x[index]   #For single item deletion

del x[start : stop]   #For Mutiple item deletion

del x   #For list deletion

Pop

The pop() method removes the specified index.

Syntax

X.pop(index)

If you will not specify index it will remove last element from the list

Remove

The remove() method removes the specified item.

Syntax

X.remove(value)

Clear

  • The clear() method empties the list.
  • The list still remains, but it has no content.
  • Syntax : X.clear()

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *