Python List

Introduction to Lists

Imagine a shopping list where you jot down items you need to buy. In Python, lists are similar, they are ordered collections of items that can hold various data types like numbers, text, or even other lists! 
This makes them versatile for storing all sorts of information.


1. Creating Lists
 
This is the most common way. You place your items within square brackets, separated by commas. 

Example:

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3.14]


2. Understanding elements and data types

One of the powerful aspects of lists is their ability to hold different data types within the same list. You can mix and match integers, strings, floats, booleans, or even other lists!

For instance:

mixed_list = [10, "hello", 3.14, True]


3. Accessing elements by position

Each item in a list has a specific position, starting from index 0. You can access any element using its index within square brackets. The first item has index 0, the second item has index 1, and so on.

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

first_fruit = fruits[0]  # first_fruit will be "apple"
last_fruit = fruits[2]  # last_fruit will be "cherry"

You can also use negative indexing to access elements from the end. For example, fruits[-1] will give you the last element ("cherry") in the fruits list.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

How do you create a list in Python?

Using square brackets and separating items with commas.
Using curly braces.
Using parentheses.
Using angle brackets.
Check Answer

What types of data can a Python list hold?

Different data types including integers, strings, and other lists.
Only integers.
Only strings.
Only floats.
Check Answer

How do you access the first element in a list?

Using index 0.
Using index 1.
Using index -1.
Using index 2.
Check Answer

What does the expression fruits[-1] return in a list called fruits?

The first element in the list.
The second element in the list.
The last element in the list.
An error will occur.
Check Answer

Which of the following is a valid way to create a list in Python?

fruits = ["apple", "banana", "cherry"]
fruits = { "apple", "banana", "cherry" }
fruits = ( "apple", "banana", "cherry" )
fruits = < "apple", "banana", "cherry" >
Check Answer