Understand List[] with Python Example (2023)

Programming

Handy concept of data structure in python

Understand List[] with Python Example (1)

A list is an ordered collection of elements. It stores multiple values inside a single variable. A list can contain elements of any data type like strings and integers etc. Elements of a list are placed inside square brackets ([]). A list can contain elements of the same type, different types, or duplicates.

There are different ways on how to use a list let us look at a few:

Creating a list

Creating a list is very simple. In a list, we have to always mention a variable to store the elements. Let us look at some types of creating a list:

1. Creating empty lista = []2. Creating an integer/ string lista = [1, 2, 3, 4]3.Creating a mixed lista = [5, “hello”, 65, “welcome”]4. Creating a nested lista = [5, 8 , 3, [“hello”, “hi”], 45]

Explanation: The above example states an example of simple lists where all the elements are stored in the variable “a”.

Accessing a list

We have created a list. But now we want to display or print only the required ones as the output. Indexing is the way to do it. Each element in a list has an index value and using that value, elements in the list can be accessed. There are 2 types of indexing, positive and negative. Let us dive deep into each of them.

  1. Positive Indexing

Positive indexing means the elements in a list are accessed from left to right. Here the indices start from “0”. Let us explore this concept with a simple example:

a = [1, 3, 5, 8, “Hello”]
↑ ↑ ↑ ↑ ↑
0 1 2 3 4
print(a[0])
print(a[4])
Output:
1
Hello

Explanation: In the above list “a”, there are five elements. Here the index value starts with “0”(left to right) and ends with “4”.

  • In the first print statement, the output will be displayed as 1 because “a[0]” means we are accessing an element with an index value “0”. The same process applies to the second statement also.

2. Negative Indexing

Negative indexing means the elements in a list are accessed from right to left. Here the indices start from “-1”. Let us explore this concept with a simple example:

a = [1, 2, 5, 4, “welcome”]
↑ ↑ ↑ ↑ ↑
-5 -4 -3 -2 -1
print(a[-1])
print(a[-3])
Output:
welcome
5

Explanation:

Here we can see that a list can also be accessed from right to left. In the first print statement, the output will be displayed as “welcome” because “a[-1]” means that we are accessing an element with index value “-1”. This applies to the second print statement also.

3. Nested Indexing

Nested indexing is of a similar concept as above. Let us look at an example:

a = [“atom”, “cell”, [1, 2, 3]]
↑ ↑ ↑
0 1 2
print(a[0][3])
print([2][0])
Output:
m
1

Explanation:

In the 1st print statement, “a[0][3]” means that we are accessing an element allocated in the 0th position i.e ‘atom.’ And in that word, we are accessing an element having index “3” which is the letter “m” The same applies to the second statement.

4. Slicing lists

A list is sliced to access a range of elements. “:” symbol is used here to specify the range of elements that have to be accessed. Let us explore this concept using a simple example:

a = [“toy”, “lock”, 23, 65, 89]print(a[0:2])
print(a[:-2])
print(a[2:])
print(a[:])
Output:
[‘toy’, ‘lock’, 23]
[‘toy’, ‘lock’, 23]
[23, 65, 89]
[“toy”, “lock”, 23, 65, 89]

Explanation:

The above program shows different ways to access a range of elements from a list.

  • The 1st print statement prints the list from index position 0–2.
  • The 2nd print statement prints all the elements from the list except the last two elements.
  • The 3rd print statement prints all the elements from the list starting from position 2.
  • The 4th print statement prints all the elements present in the list.
Python: Zero to Hero with ExamplesA handbook guide for python beginnerspub.towardsai.net

Add/modify a list

In a list, if there is a requirement to add an element to it, it is not necessary to do it manually. An element can be added to the list using the python program. Let us understand how:

a = [56, 78, 99]
a[1] = “hello”
print(a)
a.append(4)
print(a)
a.extend([5, 6, 77])
print(a)
Output:
[56, “hello”, 99]
[56, “hello”, 99, 4]
[56, “hello”, 99, 5, 5, 6, 77]

Explanation:

In the 1st code snippet, the word “hello” gets replaced by 78 which is in the index value 1. To this list, the value “4” gets added to the end of the list(2nd code snippet). Followed by, the list “[5, 6, 7]” gets added to the end of the list in the code snippet.

Delete or remove list items

If there is a requirement to remove an element in a list, it is unnecessary to do it manually. Unwanted elements in a list can be removed using the python program. Let us understand using an example:

a = [45, 89, 67, 88, 65,45]del a[2]
print(a)
del a[2:4]
print(a)
del a
print (a)
Output:
[45, 89, 88, 65, 45]
[45, 89]
Traceback (most recent call last):
File “<string>”, line 9, in <module>
NameError: name ‘a’ is not defined

Explanation:

In the 1st program, the element having the index value “2” will get deleted. Now from this deleted list, elements in index positions 2 to 4 will be deleted. And now, the last code snippet deletes all the elements of what was left in the list.

List methods

There are several list methods used in python such as append(), extend(), clear() etc. These methods make a program much easier to understand also. Let us look at these methods with a few examples:

  1. append(): An append() method adds a single element to the end of the list

Program:

a = [‘e’, ‘l’, ‘i’, ’n’, ‘o’, ‘s’, ‘u’]a.append([‘k’, ‘i’, ’n’, ‘g’])
print(a)
Output:
[‘e’, ‘l’, ‘i’, ’n’, ‘o’, ‘s’, ‘u’, [‘k’, ‘i’, ’n’, ‘g’]]

2. extend(): An extend() method adds any number of a specified list of elements to the end of the list.

Program:

a = [‘p’, ‘l’, ‘a’, ’n’, ‘t’, ‘s’, ‘s’]a.extend([‘k’, ‘i’, ’n’, ‘g’])
print(a)
Output:
[‘p’, ‘l’, ‘a’, ’n’, ‘t’, ‘s’, ‘s’, ‘k’, ‘i’, ’n’, ‘g’]

3. clear(): The clear() method removes all the elements present in the list.

Program:

a = [‘t’, ‘o’, ‘y’]
a.clear()
Output:
[]

4. remove(): The remove() method deletes one element/item from the list.

Program:

a = [‘t’, ‘o’, ‘y’]
a.remove(‘y’)
print(a)Output:
[‘t’, ‘o’]

5. pop(): The pop() method removes and returns the last value either from the list or the given index value.

Program:

a = [‘t’, ‘o’, ‘y’, ‘s’]print(a.pop(3))Output:
s

6. insert(): The insert() method inserts an element at the defined index.

Program:

num = [34, 35, 37]num.insert(2, 36)
print(num)
Output:
[34, 35, 36, 37]

7. index(): The index() method returns the first matched element in the list.

Program:

num = [34, 35, 38]print(num.index(38))Output:
2

8. count(): The count() method returns the number of elements that is passed as an argument.

Program:

d = [1,2,3,4,3,5,3]print(d.count(3))Output:
3

9. sort(): The sort() method sorts the list in ascending order.

Program:

r = [5,66,3,8,1]r.sort()
print(r)
Output:
[1, 3, 5, 8, 66]

10. reverse(): The reverse() method reverses the order of elements present in the list.

Program:

e = [1, 3, 5, 8, 66]e.reverse()
print(e)
Output:
[66, 8, 5, 3, 1]

List membership test

The list membership test is a test to check whether the defined element is present in the list or not.

Program:

animal = [ ‘a’, ’n’, ‘i’, ‘t’, ‘a’, ‘l’, ‘y’]print(‘a’ in animal)
print(‘b’ in animal)
Output
True
False

Explanation:

In the above program, the 1st statement checks whether the element ‘a’ is present in the list. Since ‘a’ is found in the list, it returns the output as True. A similar process applies to the 2nd statement also.

Become a Data Scientist in 2021 with These Following StepsFundamental points required to be on a path of data scientistpub.towardsai.net

Iteration using list

Iteration using list means using ‘for’ loops. The for loop helps to print the statement more than once. Let us explore this concept using a simple example:

for animal in ["Tiger", "Lion", "Hyena", "Zebra"]:
print(animal, “is an animal”)
Output:
Tiger is an animal
Lion is an animal
Hyena is an animal
Zebra is an animal

Explanation: The above program is a looping program (using for loop). Here, the program prints the output till it reaches the end of the list.

I hope you like the article. Reach me on my LinkedIn and twitter.

1. NLP — Zero to Hero with Python
2. Python Data Structures Data-types and Objects
3. Exception Handling Concepts in Python
4. Why LSTM more useful than RNN in Deep Learning?
5. Neural Networks: The Rise of Recurrent Neural Networks
6. Fully Explained Linear Regression with Python
7. Fully Explained Logistic Regression with Python
8. Differences Between concat(), merge() and join() with Python
9. Data Wrangling With Python — Part 1
10. Confusion Matrix in Machine Learning

Top Articles
Latest Posts
Article information

Author: Mr. See Jast

Last Updated: 12/22/2022

Views: 5929

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.