fbpx

Creating and Accessing Lists

What is a list?

In Python, a list is a collection of elements or items. It is one of the most commonly used data structures in Python, and it is used to hold a collection of items in a single variable.

Lists in Python are created using square brackets [], and the items or elements are separated by commas. For example, we can create a list of strings as follows:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]
				
			

Lists are useful because rather than creating individual variables for each of the five students above, we can create a single list variable that holds them all. This helps us manage complexity within our code and make it more readable.

Lists can contain any type of data, including integers, floats, strings, Booleans, and even other lists. For example, we can create a list of mixed data types as follows:

				
					mixed_list = [1, "two", True, 3.14, [4, 5, 6]]

				
			

Indexing Lists

In order to access an individual element in a list, we need to know its “index”, or its order within the list. In Python, and most other other programming languages, we always start indexing at 0, and counting up by one each time. For example, if I wanted to just return the first value in a list, I could do the following:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]
print(students[0]) # prints out Luke
				
			

Notice that we reference the name of the list and put the index within hard brackets to access the value we desire. We could also use similar syntax to update the value of an element as follows:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]
print(students[0]) # prints out Luke

# change Chewie's name to Chewbacca:
students[3] = "Chewbacca"
				
			

It is also possible to index from the back of a list (this may be useful in certain circumstances), by using a negative index value. The last value in a list can be accessed by puttingĀ -1 in hard brackets, and working our way forward from there.

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

print(students[-1]) # prints out the last element in the list (Lando)
print(students[-3]) # counting from the back of list, this should print Han
				
			

The len() Attribute

The len() attribute allows us to find the length of a given list without having to count out all the elements. This will prove to be very helpful as we continue to learn later topics like lists. You can access the len() attribute like so:

				
					test_scores = [92, 83, 88, 71, 79, 100, 95, 67, 70, 91]

print(len(test_scores)) # prints length of list, which is 10
				
			

Replit Practice

Loading...