Python

List in Python

In this article, we will explain List in Python through examples.

1. Introduction

Lists are used to store multiple items in a single variable. List items are indexed, the first item has index [0], the second item has an index [1], etc. Also, a list is ordered, which means that the items have a defined order, and changeable, meaning that we can change, add and remove items in a list after it has been created.

2. Create a List and Access Its Elements

Lists are created using square brackets []. List items are indexed and you can access them by referring to the index number. The first item has an index of 0. Furthermore, we can use negative indexing (-1 refers to the last item, -2 refers to the second-last item, etc). You can specify a range of indexes by specifying where to start(included) and where to end(not included) the range. When specifying a range, the return value will be new list with the specified items. Also, this is how you can slice a list.

pythonList.py

myList = ["car", "banana", "UFO", "red", 666]
print(myList)
print(myList[1])
print(myList[-1])
print(myList[2:4])
python list - First Example Output
Fig. 1: First Example Output

3. Add/Change List Elements

To add an item to the end of the list, use the append() method, and to insert an item at a specified index, use the insert() method. Also, to append elements from another list to the current list, use the extend() method. Last but not least, we can change the value of a specific item, referring to the index number.

pythonList.py

myList = ["car", "banana", "UFO", "red", 666]
myList[2] = 50
print(myList)
myList.insert(2, "inserted")
print(myList)
myList.append(True)
print(myList)
tmpList = [60, False, "papaya"]
print(tmpList)
myList.extend(tmpList)
print(myList)
python list - Second Example Output
Fig. 2: Second Example Output

4. Delete/Remove List Elements

The remove() method removes the specified item. The pop() method removes the specified index. If you do not specify the index, the pop() method removes the last item. The del keyword also removes the specified index. The del keyword can also delete the list completely.

pythonList.py

myList = ["car", "banana", "UFO", "red", 666]
myList.insert(0, "banana")
print(myList)
myList.remove("banana")
print(myList)
myList.pop(1)
print(myList)
del myList
python list - Third Example Output
Fig. 3: Third Example Output

5. Comprehension in List

List comprehension in python offers to shorten the regular syntax when we want to create a new list based on the values of an existing list. The syntax given in the below example expects a condition like a filter that only accepts the items that evaluate to true. Comprehension offers more time and space-efficient loops that require few lines of code. It transforms an iterative statement into a formula.

pythonList.py

myList = ["car", "banana", "UFO", "red", 666]
# syntax =
# newlist = [expression for item in iterable if condition == True]
# returns the new list while keeping the old list as same


# 1. iterating through a string using list comprehension
alphabets = [char for char in "javacodegeeks"]
print("alphabets are= {}\n".format(alphabets))

# 2. iterating through a list using list comprehension
cars = [
    "bmw",
    "audi",
    "mercedes",
    "ferrari",
    "bugati",
    "viper",
    "tesla"
]

new_cars = [item for item in cars]
print("cars= {}\n".format(new_cars))

# 3. conditionals in list comprehension
filtered_cars = [item for item in cars if "a" in item]
print("filtered cars= {}\n".format(filtered_cars))

# 4. if else in list comprehension
obj = ["even" if i % 2 == 0 else "odd" for i in range(20)]
print(obj)

6. Summary

As we can see from the examples above, lists are a very useful and simple way to store data in a sequence. It is more akin to an array in other programming languages. More list methods can be found here.

7. Download Source Code

This was an example of how we can create, parse, modify and delete a list in python.

Download
You can download the full source code of this example here: List in Python

Last updated on Mar. 30th, 2022.

Odysseas Mourtzoukos

Mourtzoukos Odysseas is studying to become a software engineer, at Harokopio University of Athens. Along with his studies, he is getting involved with different projects on gaming development and web applications. He is looking forward to sharing his knowledge and experience with the world.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button