
Syntax: Lists
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
-
Create a list named
fruitscontaining the following items:'apple','banana','cherry'. -
Print the list
fruits. -
Create a list named
numberscontaining the integers from 1 to 5, using thelist()function andrange()function. -
Print the list
numbers. -
Create a list named
mixedthat contains an integer, a string, andfruitslist as its elements. -
Print the list
mixed.
HINT*: Click here for a hint
> ['apple', 'banana', 'cherry']
> [1, 2, 3, 4, 5]
> [10, 'Hello', ['apple', 'banana', 'cherry']]
SOLUTION*: Click here for an example solution
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.