Write a list in python


mylist = ["apple", "banana", "cherry"]


List

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Example

Create a List:

thislist = ["apple", "banana", "cherry"]
print(thislist)

Try it Yourself »


List Items

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.


Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items will not change.


Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.


Allow Duplicates

Since lists are indexed, lists can have items with the same value:

Example

Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

Try it Yourself »



List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]
print(len(thislist))

Try it Yourself »


List Items - Data Types

List items can be of any data type:

Example

String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

Try it Yourself »

A list can contain different data types:

Example

A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

Try it Yourself »


type()

From Python's perspective, lists are defined as objects with the data type 'list':

Example

What is the data type of a list?

mylist = ["apple", "banana", "cherry"]
print(type(mylist))

Try it Yourself »


The list() Constructor

It is also possible to use the list() constructor when creating a new list.

Example

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

Try it Yourself »


Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.



Knowing how to write the elements of a list to a file in Python can be handy. In this tutorial you will see how to do that in multiple ways.

A common approach to write the elements of a list to a file using Python is to first loop through the elements of the list using a for loop. Then use a file object to write every element of the list to a file as part of each loop iteration. The file object needs to be opened in write mode.

There are many scenarios in which writing the items of a list to a file can turn out useful.

Let’s have a look at one example!

  • How to Store the Elements of a Python List in a File
  • What Error Do You See When Writing to a File Opened in Read Mode?
  • Writing a List to a File Using the With Open Statement
  • Write a List to a File Using the String Join Method
  • Writing a Python List to a File Using Writelines
  • How to Write a List to a File Using a Python Lambda
  • Conclusion

How to Store the Elements of a Python List in a File

Imagine you are building an application that needs to persist a list of items after its execution.

This might be required, for example, if every time you run your application you store data in a file and that data can be read and used the next time you run your application.

Let’s have a look at how you can take the list of strings below and store each string in a file using Python.

months = ['January', 'February', 'March', 'April']

We will open a file object in write mode and then use a for loop to write each element to the file:

output_file = open('months.txt', 'w')

for month in months:
    output_file.write(month)

output_file.close()

Using the Python open() built-in function we open a new file in write mode. Each iteration of the for loop writes a month to the file.

Then, we close the file object once we have written all the elements in the list to it.

Now, let’s have a look at how the content of the file looks like using the cat command:

$ cat months.txt
JanuaryFebruaryMarchApril 

It looks like we are missing new line characters at the end of each line, let’s add it to the write method in each iteration of the for loop:

output_file = open('months.txt', 'w')

for month in months:
    output_file.write(month + '\n')

output_file.close()

The output looks a lot better now:

$ cat months.txt 
January
February
March
April 

What Error Do You See When Writing to a File Opened in Read Mode?

I want to see what happens if we don’t open the file explicitly in write mode.

Replace the following line in your Python code:

output_file = open('months.txt', 'w')

With the following…

…notice that we have removed the second parameter passed to the open() function that was telling the function to open the file in write mode:

output_file = open('months.txt')

Here is the error we get when we run our code if we don’t delete the months.txt file created in the previous example:

$ python write_list_to_file.py
Traceback (most recent call last):
  File "write_list_to_file.py", line 6, in 
    output_file.write(month + '\n')
IOError: File not open for writing

The error tells us that the file has not been opened for writing. Without passing the second parameter to the open() function we have opened our file in read mode.

If you delete the months.txt file and rerun the program you get a different error:

python write_list_to_file.py
Traceback (most recent call last):
  File "write_list_to_file.py", line 3, in 
    output_file = open('months.txt')
IOError: [Errno 2] No such file or directory: 'months.txt'

The Python interpreter tries to open the file in read mode but considering that the file doesn’t exist we get back the “No such file or directory” error.

Writing a List to a File Using the With Open Statement

Instead of remembering to close the file object after the end of the for loop, we can use the Python with open statement.

This creates a context manager that automatically closes the file object when we don’t need it anymore.

Here is how our Python code becomes…

months = ['January', 'February', 'March', 'April']

with open('months.txt', 'w') as output_file:
    for month in months:
        output_file.write(month + '\n')

A lot more concise!

Execute it and confirm that every element in the list is written to the file as expected.

Write a List to a File Using the String Join Method

I wonder if I can replace the for loop with a single line that uses the string join() method.

The string join method joins the elements of a sequence into a single string where every element is separated from another by the string the join method is applied to.

Maybe it’s easier to show it in the Python shell 🙂

>>> months = ['January', 'February', 'March', 'April']
>>> '#'.join(months)
'January#February#March#April'         

I have used the # character in this example because in this way it’s easier to see how the # is used to separate elements in the list.

Notice that the separation character # doesn’t appear after the last element.

So, this is the result if we use this approach in our program and replace the # character with the new line character:

output_file = open('months.txt', 'w')
output_file.write('\n'.join(months))
output_file.close()

The result is:

$ cat months.txt
January
February
March
April$

The dollar at the end of the last line is the shell itself considering that the new line character is not present at the end of the last line.

So, this method kind of works but it’s not as good as the for loop because it doesn’t add a new line character in the last line of the file.

Writing a Python List to a File Using Writelines

Python file object provide a method called writelines() that writes a sequence of strings to a file.

It feels it could be another good way to do this, let’s give it a try!

output_file = open('months.txt', 'w')
output_file.writelines(months)
output_file.close()

Here is the output when I run the program:

cat months.txt 
JanuaryFebruaryMarchApril$

Hmmm…this doesn’t look right.

The file writelines() method doesn’t add any line separators.

I wonder why?!?

What we could do is adding the new line character after each element in the list and then pass the list to the writelines method.

Let’s use a list comprehension to do that:

output_file = open('months.txt', 'w')
months = ["{}\n".format(month) for month in months]
output_file.writelines(months)
output_file.close()

You can see that we are also using the string format() method to add the new line character at the end of each string in the list.

The output we get back looks good:

$ cat months.txt
January
February
March
April  

The final approach we will use to write the strings in our list to a file will also use a lambda function and the map function.

Using lambdas is not really necessary, we are doing it in this tutorial as an exercise to refresh more advanced Python concepts.

Below you can see the syntax of the map function:

map(functioniterable...)

The map function applies the function passed as first parameter to every item of the iterable. In this case the function will be a lambda function that appends the new line character to a given string and writes the result to a file object.

We will use this as a generic approach to write every item in the list followed by a newline to the output file.

Here is the lambda function to use:

lambda x: output_file.write(x + '\n')

And now let’s pass the lambda to the map function:

months = ['January', 'February', 'March', 'April']
output_file = open('months.txt', 'w')
map(lambda x: output_file.write(x + '\n'), months)
output_file.close()

Let’s confirm if the output is correct…

$ cat months.txt
January
February
March
April  

Yes it is!

Conclusion

We have seen so many different approaches to write the elements of a Python list to a file.

It has been a good exercise to practice multiple ways of solving the same problem in Python.

Let me know in the comments, which one do you prefer? 🙂

Write a list in python

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

What is a list () in Python?

List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

How do you write a list to a file?

Use file..
a_list = ["abc", "def", "ghi"].
textfile = open("a_file.txt", "w").
for element in a_list:.
textfile. write(element + "\n").
textfile. close().

How do you make a 3 list in Python?

Python Lists list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"]; Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

How do you write a list of data to a text file in Python?

Method 2: write in a Text file In Python using writelines() The file is opened with the open() method in w mode within the with block, the argument will write text to an existing text file with the help of readlines(). The with block ensures that once the entire block is executed the file is closed automatically.