Python lists

/ #Python


Python has something called lists which is a collection of objects.

What is a list?

A list is a collection of objects. The objects can be strings, letters, numbers and so much more. You use them to store information.

A simple example

Lists are defined in square brackets [ ]

>>> animals = ['cow', 'bear', 'sheep', 'antilope']
>>> animals[1]
'bear'
>>> animals[-1]
'antilope'

I used the Python interpreter to quickly show what a list looks like and how to access the values.

To get "bear", you type the name of the list and add two square brackets after it, inside the square brackets, you add the index or indices you want. "bear" is at index number 1. To access the last entry of the list, you use "-1".

Slicing arrays

Slicing arrays works in the exact same way as with strings.

>>> animals = ['cow', 'bear', 'sheep', 'antilope']
>>> print(animals[0:2])
['cow', 'bear']
>>> print(animals[3])
['antilope']
>>> animals[3] = 'lion'
>>> print(animals[3])
['lion']

Looping

Looping through a list is very easy. We use a function called 'for'.

>>> animals = ['cow', 'bear', 'sheep', 'antilope']
>>> for animal in animals: # Assign the variable animal to the current index in animals
>>> ... print(animal)
cow
bear
sheep
antilope

Check if list contains element

To check if an element exist in a list, just use a function called 'in'.

>>> animals = ['cow', 'bear', 'sheep', 'antilope']
>>> if 'cow' in animals: print('Result!')
Result!
Another way of creating lists is building them up this way:
>>> animals = [ ]
>>> animals.append('lion')
>>> animals.append('cat')
>>> animals
['lion','cat']

Next we are going to talk about is all the methods that comes with list and how to use them.

Methods

Lists also comes with several very useful methods. Here's some examples with comments.

>>> animals = ['cow', 'bear', 'sheep', 'antilope']
>>> animals.append('lion') # Appends a element at the end
>>> print(animals)
['cow', 'bear', 'sheep', 'antilope', 'lion']
>>> animals.insert(0, 'tiger') # Insert a element at index 0
>>> print(animals)
['tiger', 'cow', 'bear', 'sheep', 'antilope', 'lion']
>>> animals.remove('sheep') # Searches and removes element with value 'sheep'

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.