Python List

In python, a list is a dynamic collection of an ordered item that is changeable. In short, you can add as many items as you can(provided below RAM limit) and those items will be in the same order as you added and can be changed. The list can have similar items (only numbers, only strings, only, only dictionaries, etc) or a combination of items(numbers, strings,  list, dictionaries, etc). We will look at the dictionary in the next post. 

Syntax:

List can be using square bracket (  [ ]  ) in python. Let’s see few example of list. 

# an empty list
empty_list = []

# list with similar items
similar_item_list = [1, 2, 3, 4, 5, 6]

# list with different items
different_item_list = [82, 95, 'First name', 'Last name', 67.77]

List can not only have numbers and string but can also have other datatypes like dictionary, set, tuple or even list. Let’s see some example of list with different data types

# list with list inside
list_with_list_inside = [22, 'email', [305, 3.5, 'inside item']]

# list with dictionary, tuple, set, list
list_with_dynamic_items = [{'one': 1, 'two': 2}, (2, 3, 4), {1, 2, 3, 4}, [1, 2, 3, 4]]

Indexing/Selecting item in list

Similar to strings in python list also support both positive indexing and negative indexing. Indexing is simply referring to an item inside a list. This has three main purpose one is to get the specific item inside the list(to view item) and another one is to update the list and, third is to delete the item.

Indexing starts from 0 to N for positive indexing where 0 refers to the first item, 1 refers to second item and so on. Where as, negative indexing starts from -1 and goes to -N (minus N). -1 index represents the last item in the list.

Let’s see following diagram to understand it in detail.

List Indexing in python

Example

my_list = ['One', 'Two', 'Three', 'Four']

# positive indexing
print(my_list[0])  # gets first element i.e. 'One'
print(my_list[1])  # gets second element i.e. 'Two'
print(my_list[2])  # gets third element i.e. 'Three'

# negative indexing
print(my_list[-1])  # gets last element i.e. 'Four'
print(my_list[-2])  # gets second last element i.e. 'Three'

Output:

One
Two
Three
Four
Three

Slicing in a list

Slicing is a technique use to grab range of items from a list. Slicing technique are similar to that we saw in string. We use color ( : ) operator to get a slice. Let’s see through an example.

my_list = ['One', 'Two', 'Three', 'Four']
second_small_list = my_list[2:4]
print(second_small_list)

Output:

['Three', 'Four']

This second_small_list will have item from the 2nd index(from positive indexing, i.e third item) to third index (i.e. 4-1 =3). If we give 4 we get index from 2nd to 3rd index. We can also not provide the first or second parameter in the colon syntax. If we leave first index value( in our case 2) empty it means item from the beginning. And, if we leave 2nd index item (i.e. 4) empty we mean all the way to the last item. Let’s see various ways to slice an item.

my_list = ['One', 'Two', 'Three', 'Four']
# from first item to 3rd item
first_to_3rd_item = my_list[:3]
print(first_to_3rd_item)

# from second item to last item
second_to_last_item = my_list[2:]
print(second_to_last_item)

# all item
all_item = my_list[:]
print(all_item)

Output:

['One', 'Two', 'Three']
['Three', 'Four']
['One', 'Two', 'Three', 'Four']

Adding item to a list

We can add item to a list following technique

  1. using  .append()  method
  2. using  .insert()  method

We can add item using .append() method and .insert(). Append method adds item to the last where as insert method adds item to specific index position.

Syntax for append() method

my_list.append(item)

Syntax for insert() method

my_list.insert(index, item)

Let’s see an example below:

my_list = [1, 2, 3, 4]

# using append
my_list.append('Fifth element')
print(my_list)

# insert in 2nd index position
my_list.insert(2, '2nd item')
print(my_list)

Output:

[1, 2, 3, 4, 'Fifth element']
[1, 2, '2nd item', 3, 4, 'Fifth element']

Updating item in a list

updating item in a list is simple we refer to the item which we want to update using indexing value and then assign the new value using equal operator.

Let’s see an example

my_list = [1, 2, 3, 4]

my_list[2] = 'Updated value'
print(my_list)

Output:

[1, 2, 'Updated value', 4]

Deleting item from a list

We use  del    keyword to delete item from a list. 

Syntax

del my_list[index] 

Example:

my_list = [1, 2, 3, 4]

del my_list[0]  # deleting first item i.e. 1
print(my_list)
del my_list[2]  # deleting 3rd item i.e.4
print(my_list)

Output:

[2, 3, 4]
[2, 3]

If we want to delete all item from a list we can use .clear() method in a list. For example,

my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list)

Output:

[]

We can also .pop() method on a list to remove last item from a list. For instance,

my_list = [1, 2, 3, 4]
last_item =  my_list.pop()
print("last_item=", last_item)
print("original my_list=",my_list)

Output:

last_item= 4
original my_list= [1, 2, 3]

Looping in a list

We can use loops to get access item in a list. List is iterable collection of items. For example,

my_list = [1, 2, 3, 4]
for item in my_list:
    print(item)

Output:

1
2
3
4

If you want to go through item and also want to know index then we can use  enumerate()   method. 

Syntax for enumerate()

enumerate(my_list,[start])  

enumerate take a list as a argument. start is optional by default if we don’t pass start value it will give item from 0 index. enumerate return tuple having two values including index and value. Let’s see an example

planets = ['mars', 'venus', 'earth']
for index, item in enumerate(planets):
    print("index is ", index, ', value is ', item)

print('enumerate with 1 as index value')
# enumerate passing 1 as initial index value
for index, item in enumerate(planets, start=1):
    print("index is ", index, ', value is ', item)

Output:

index is  0 , value is  mars
index is  1 , value is  venus
index is  2 , value is  earth
enumerate with 1 as index value
index is  1 , value is  mars
index is  2 , value is  venus
index is  3 , value is  earth

Length of a list

You can use  len(listitem)  function to calibrate length of list. For example

planets = ['mars', 'venus', 'earth']
print(len(planets))

Output:

3

Leave a Reply

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