Python list: Every possible option

This post understands that you now have a very basic understanding of what a list is. If not, I would recommend reading the basics of python lists.

The most common data operations that we do on any data structure is, CRUD

Create – Read – Update – Delete

Let’s see how we do this in python lists,

Create

You can add data to list using append method.

# List Init
l = list()

# Getting the type of variable l  
type(l)
list

# Now let's print the empty list
print(l) 
[]

# Adds a new value 10 to the list
l.append(10)

# Adds another value of type string to the list
l.append('python-list')

# Now let's see what the list contain
print(l)
[10, 'python-list']

# We can even  merge two lists
old_list = [1, 2, 3, 4, 5]

l.extend(old_list)

print(l)
[10, 'python-list', 1, 2, 3, 4, 5]
 
# Or we can add the complete list as a value to a list
l.append(old_list)

print(l)
[10, 'python-list', 1, 2, 3, 4, 5, [1, 2, 3, 4, 5]]

Take away

  1. append -> adds data to the list, irrespective of its type
  2. extend -> adds each element in the iterable data

Read

We can read the element of a list using its index / position of the element in the list.

Leave a reply:

Your email address will not be published.