CodeGym /Courses /Python SELF EN /Working with Lists

Working with Lists

Python SELF EN
Level 7 , Lesson 2
Available

2.1 Determining the Length of a List

Now that we've learned how to create lists, the next task is to determine the number of elements in a list. In Python, you use a special function for this — len().

Example of using the len() function:


my_list = [10, 20, 30, 40]
print(len(my_list))  # Outputs 4

You can pass either a variable containing a list or the list itself directly to the len() function. Examples:


print(len([]))  # Outputs 0
print(len([1, 2, 3]))  # Outputs 3
print(len([[1, 2, 3]]))  # Outputs 1

The len() function is very efficient and can handle even very large lists quickly because Python keeps track of the list size in the list object itself.

2.2 The type() Function

If you're not sure whether a variable is a list, you can use the type() function.

Example:


my_list = [1, 2.5, 'string', [3, 4]]
print(type(my_list))  # Outputs: <class 'list'>

Checking if a variable is of the desired type looks like this:


my_list = [1, 2.5, 'string', [3, 4]]
if type(my_list) == list:
    print("List!")  # Outputs: List!

2.3 Accessing an Element: [index]

We've learned how to determine the length of a list, now let's figure out how to work with its elements. A list in Python is an ordered collection of elements where each element has its index, starting from zero.

Important! The element number in a list in Python (and many programming languages) is called an index. To avoid confusion, remember that the first element has an index of 0, the second — 1, and so on. If you have 10 elements in a list, they'll have indices from 0 to 9.

To access a list element, use square brackets with the element's index. The general form of such an operation is:


List[index]

Example:


my_list = [10, 20, 30, 40, 50]
print(my_list[0])  # Outputs 10
print(my_list[1])  # Outputs 20
print(my_list[2])  # Outputs 30

Just like with strings, lists support negative indices.

Accessing the last element of the list:


my_list = [10, 20, 30, 40, 50]
print(my_list[-1])  # Outputs 50

Accessing the second-to-last element of the list:


my_list = [10, 20, 30, 40, 50]
print(my_list[-2])  # Outputs 40
2
Task
Python SELF EN, level 7, lesson 2
Locked
Random Program
Random Program
2
Task
Python SELF EN, level 7, lesson 2
Locked
The Fifth Element.
The Fifth Element.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION