Introduction to Python Resources

Begin your free Python journey now,
at your own pace

check

Syntax: Lists

check

Sequential lists of values in Python.


Python Lists

Lists are one of Python's built-in data collection types, and they are used widely in data analysis processes. A list represents a collection of values with a defined order, where individual values are referenced by their position in the list.

Lists are created by enclosing comma-separated values inside square brackets [], or by using the list() function.

Creating a List with Square Brackets

list1 = [1, 2, 3, 4, 5]
print(list1)
> [1, 2, 3, 4, 5]

In the above code, we've created a list list1 of integers.

Creating a List with list() Function

list2 = list(('apple', 'banana', 'cherry'))
print(list2)

> ['apple', 'banana', 'cherry']

In the above code, we've created a list list2 of strings using the list() function.

Lists in Python can contain elements of different types. For example, a single list can contain elements like integers, strings, and even other lists.

mixed_list = [1, 'two', [3, 4, 5]]
print(mixed_list)

> [1, 'two', [3, 4, 5]]

In the above code, mixed_list contains an integer, a string, and another list.

Practice: Creating Lists

  1. Create a list named fruits containing the following items: 'apple', 'banana', 'cherry'.

  2. Print the list fruits.

  3. Create a list named numbers containing the integers from 1 to 5, using the list() function and range() function.

  4. Print the list numbers.

  5. Create a list named mixed that contains an integer, a string, and fruits list as its elements.

  6. Print the list mixed.

HINT*: Click here for a hint
*Hints are best viewed after completing a task, or after spending some time and effort attempting it. In cases where a hint contains example output, it is important to understand why it is correct, as there may be many correct outputs.
> ['apple', 'banana', 'cherry']
> [1, 2, 3, 4, 5]
> [10, 'Hello', ['apple', 'banana', 'cherry']]
SOLUTION*: Click here for an example solution
*Example solutions are best viewed after completing a task and understanding the outcome. In most cases, there are multiple ways to complete a task, and the example solution is only one example.
fruits = ['apple', 'banana', 'cherry']
print(fruits)

numbers = list(range(1, 6))
print(numbers)

mixed = [10, 'Hello', fruits]
print(mixed)

Excellent! You're now familiar with the concept of lists in Python, a key component of data structures. In the upcoming lessons, we'll delve deeper into lists and other data structures.