Python List

Python has a built in data types for storing list of values of same type usually.

The built in data types are List, Set, Tuple and dictionary.

In this post I am going to talk about List data type.

Syntax:


list_name = [....]
#Or through list constructor
list_name = list ((...))

The first one is safer approach to create list.

# An example of python list (different types)


# creating a list of int values 
list1 = [1, 2, 3, 4, 5]

# creating a list of string values
list2 = ["Java", "Python", "C++", "Rust,"]

# Creating a list of boolean values
list3 = [true, false, false, true]

# creating a list of different types
list4 ['A', 40, "years", "old", false] 

# Accessing data members from list.

First of all, list type is Index based. Thus, we can access the list data members using the index number. Index is start from 0. Means, first member is list[0], second member is list[1] and so on.

In the following example, we create a list and access the data members using their appropriate index number.

# creating a list of same type


languages = ["Java", "JavaScript", "Python", "C++", "Rust"]

print("First member: ", languages[0])
print("Second member: ", languages[1])
print("Last Member: ", languages[-1])

After running the above example file, You will get the following output:


First member:  Java
Second member:  JavaScript
Last Member:  Rust

So, for accessing the first element we use the index [0], for second element index [1]. Negative indexing is also possible, but it starts from the end of the list. like, [-1] retrieve the last element of the list.

Yes, other approaches also follow to access the list data members in python.

We can use the built in len() function to access the last data member of list. Such as,


list = [1, 2, 3, 4, 5]
# access the last element using built in len function
print(list(len(list) - 1) # output: 5, last element

How?

Built in len() function, returns the length of the list. And, list elements are always one less from the length of the list. So, the last element of the above list is 4th index, (as length is 5. Therefore,

list[len(list) -] == list[4] 

# List Methods

There are lot of built in methods available to work with list or list elements in python.

I am going to describe few of them. (Only based on the importance)

MethodsDescriptionExample
append(x)add a given item to the end of the list lang = ["Java", "Python"] lang.append("Rust") # Output: Java Rust Python
insert(index, el) add a new item to a given position. Required 2 arguments. First argument shows the index number and second argument is the value, that will be added. lang = ["Java", "Python", "C++"] # add a new element to 1st position (index 0) lang.insert(0, "Go"] # Output: Go Java Python C++
remove(el) # required one argument Remove the specified element lang = ["Java", "Python", "Ruby", "Rust"] lang.remove() print(lang) # remove the last member lang.remove("Rust") print(lang) # Output: ['Java', 'Python', 'Ruby']
pop(index): remove an element from the list based on index number. If no index is specified, last element will be removed. lang1 = ["Java", "Python", "C++"] lang1.pop() # by default last element is removed # Output: Java Python C++ # Remove the 1st element from the list lang2 = ["Java", "Python", "C++"] lang2.pop(0) # Note: index stars from 0 # Output: Python C++
clear() remove all the elements from the list, equivalent to: del list[:]. But the list itself will not be deleted entirely. Thus, when you print list, it returns empty list or if you use len(list), it returns 0 lang = ["Java", "Python", "C++"] lang.clear() # all the elements have been removed print(lang) # return empty list # Output: [] print(len(lang)) # Output: 0
count(el) # required an element to count returns the number of the given element, (How many times a specific element occurs in a list) lang = ["Java", "Python", "C++", "Java"] java = lang.count("Java") print(java) # returns 2, as java occurs 2 times in the list. # Output: 2
sort() or sorted() sort the items of the list either escending (default) or descending (logic required). names = ["Elena", "Alfred", "Bhumi", "Fredrick", "Cobult"] # Sort the names [] list (ascending by default) # Sort the names [] list (ascending by default) names.sort() # if you put it in a variable, it returns None (in this case you can use sorted() method than sort() print(names) # Output: ['Alfred', 'Bhumi', 'Cobult', 'Elena', 'Fredrick'] # Sort the names [] list descending order names.sort(reverse = True) print(names) # Output: ['Fredrick', 'Elena', 'Cobult', 'Bhumi', 'Alfred']
reverse() reverse elements of the list in place. lang = ["Java", "Python", "C++"] lang.reverse() print(lang) # Output: ['C++', 'Python', 'Java']
copy() return shallow copy of the list, equivalent to list[:] lang = ["Java", "Python", "Rust"] copy_list = lang.copy() # new list will return print(copy_list) # Output: ['Java', 'Python', 'Rust']

# List type Features that you should remember when working on Python List

1. List is index based and ordered.
2. List is mutable (new elements have been added or removed as well)
3. Allow duplicate elements
4. Allow different data types