Evolving with Python Lists: Creation, Properties, and Operative Mastery

Introduction

Hello, future programmer! Today, we're delving into Python Lists. These versatile tools can hold multiple items together. Picture a shopping list — it consists of various individual items consolidated under one name. Our mission is to comprehend Python Lists, including their creation, modification, and operations.

Definition and Characteristics of Python Lists

Python lists are ordered collections of items. 'Ordered' implies that each item has a predetermined position, akin to the arrangement of books on a shelf. Lists can store anything — numbers, strings, or even other lists! They are mutable (you can modify them) and allow duplicates.

How to Create a List

Creating a list in Python is like packing a bag. Here, [] denotes the bag (or list), and the items are separated by commas. A list can contain various types of items — numbers, text, and even more lists! We can also create a list with the list() function:

Python
fruits = ['apple', 'banana', 'cherry'] # creates a list of three elements
numbers = list((1, 2, 3)) # creates a list of three elements - 1, 2, and 3
print(fruits, numbers)    # Outputs: ['apple', 'banana', 'cherry'] [1, 2, 3]

Accessing Elements of a List

Accessing an item in a list is as effortless as calling its position in the order, starting with 0. On top of that, to access the elements from the end, you can use a specific notation with negative indices, starting from -1. Here is an example:

Python
print(fruits[0])  # Prints the first element in the list, 'apple'.
print(fruits[1])  # Prints the second element in the list, 'banana'.
print(fruits[-1]) # Prints the last element in the list, 'cherry'.
print(fruits[-2]) # Prints the second last element in the list, 'banana'.

To retrieve multiple items, we can use a slicing mechanism, specifying the start (inclusive) and the end (exclusive) indices to include:

Python
print(fruits[0:2]) # Prints ['apple', 'banana'] - 0-th, 1-st, but not the 2-nd element
print(fruits[1:2]) # Prints ['banana'] - 1-st, but not the 2-nd element

Basic Operations on Lists

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal