DEV Community

Cover image for Learn Python: Lists
Rishi
Rishi

Posted on • Updated on

Learn Python: Lists

A list is a variable which can hold multiple values.

list_of_alpahbet = ['a','b','c','d'];
list_of_numbers= [1,2,3,4,5]
list_of_fruits = ['🍎','🍊','🍐','🥑','🥝','🍓','🍋','🍍']
mixed_list = ['a','b', 1,2, '🍓','🍋']

print(list_of_alpahbet)
print(list_of_numbers)
print(list_of_fruits)
print(mixed_list)
Enter fullscreen mode Exit fullscreen mode

Generally, you want to keep your list homogeneous. That is, you want to keep elements of similar type within a list.
In the example, the first 3 lists (list_of_alpahbet, list_of_numbers, list_of_fruits) are recommended. The 4th list (mixed_list) isn't as it is not homogeneous.

Accessing elements in a list

Elements stored within a list can be accessed via their index.
The first element always has an index value of 0.

list_of_alpahbet = ['a','b','c','d'];
list_of_numbers= [1,2,3,4,5]
list_of_fruits = ['🍎','🍊','🍐','🥑','🥝','🍓','🍋','🍍']
mixed_list = ['a','b', 1,2, '🍓','🍋']

print(list_of_alpahbet[0])
print(list_of_numbers[1])
print(list_of_fruits[2])
print(mixed_list[3])
Enter fullscreen mode Exit fullscreen mode

Nested lists

A list can be nested within another list.

# Nested lists
fruits_names = [
  ['Strawberry', '🍓'],
  ['Lemon', '🍋'],
  ['Pineapple', '🍍']
]

### Accessing the first list within a list.
print(fruits_names[0])

### Accessing the first value of the first nested list.
print(fruits_names[0][0])
Enter fullscreen mode Exit fullscreen mode

Number of elements in a list.

To evaluate the number of elements in a list, we use the len() function.

list_of_fruits = ['🍎','🍊','🍐','🥑','🥝','🍓','🍋','🍍']

print(len(list_of_fruits));
Enter fullscreen mode Exit fullscreen mode

Adding new elements to a list

Use .append() to add new elements to a list.

fruits_names = [
  ['Strawberry', '🍓'],
  ['Lemon', '🍋'],
  ['Pineapple', '🍍']
]

## Adding a new element to the list
fruits_names.append(['Avocado', '🥑'])

print(fruits_names)
Enter fullscreen mode Exit fullscreen mode

Removing from list

Use .remove() to remove an element from a list.

fruits_names = [
  ['Strawberry', '🍓'],
  ['Lemon', '🍋'],
  ['Pineapple', '🍍']
]

## Removing an element from the list
fruits_names.remove(['Lemon', '🍋'])

print(fruits_names)
Enter fullscreen mode Exit fullscreen mode



Top comments (0)