Lists in Python

Snigdha
Snigdha
Sep 2, 2018 · 4 min read

A List is a data structure in Python that holds an organized collection of items. The items, or values, that are contained within the list can be various data types themselves. In fact, you can even have lists that exist within lists.

Note that lists are created by using comma separated values between square brackets. The pattern is list_name = [item_1, item_2, item_N].

To create an empty list use: list_name = [].

Items within a list can always be accessed by index. List indices are always zero based, which means that the first item in the list will have an index of 0, the second item an index of 1, and so on. To access any item in a list using an index, simply enclose the index in square brackets directly following the list name. The pattern is list_name[index].

//Creating a List>>> fruits = [‘Apple’, ‘Mango’, ‘Orange’]
>>> fruits
[‘Apple’, ‘Mango’, ‘Orange’]
//Indexing a list>>> fruits[0]
‘Apple’
>>> fruits[1]
‘Mango’
>>> fruits[2]
‘Orange’
>>> fruits[2] = ‘Water Melon’ # replacing an element with index position
>>> fruits
[‘Apple’, ‘Mango’, ‘Water Melon’] #orange has been replaced with water mealon

Adding elements to the List :

There are three ways in which you can add elements to a list.

append(): adds only one element in a list

extend(): adds multiple elements to a list

insert(): adds an element at a particular position using an index

>>> fruits.append(“Grapes”)
>>> fruits
[‘Apple’, ‘Mango’, ‘Water Melon’, ‘Grapes’]
>>> fruits.extend([‘Orange’, ‘kiwi’, ‘pears’])
>>> fruits
[‘Apple’, ‘Mango’, ‘Water Melon’, ‘Grapes’, ‘Orange’, ‘kiwi’, ‘pears’]
>>> fruits.insert(0, ‘Banana’)
>>> fruits
[‘Banana’, ‘Apple’, ‘Mango’, ‘Water Melon’, ‘Grapes’, ‘Orange’, ‘kiwi’, ‘pears’]

Note : You can’t pass multiple arguments using insert method.

>>> fruits.insert(3, ‘Guava’, 7, ‘Avacado’)Traceback (most recent call last):
File “<pyshell#60>”, line 1, in <module>
fruits.insert(3, ‘Guava’, 7, ‘Avacado’)
TypeError: insert() takes exactly 2 arguments (4 given)

# Finding the index of a list element

>>> fruits
[‘Banana’, ‘Apple’, ‘Mango’, ‘Guava’, ‘Water Melon’, ‘Grapes’, ‘Orange’,‘kiwi’, ‘pears’]
>>> fruits_index = fruits.index(‘Mango’)
>>> fruits_index
2

Iterating a list

Iterating a list is nothing but spanning each and every element of a list.
Generally we iterate a list using a for loop.

>>> for x in fruits:
print(x)
Banana
Apple
Mango
Guava
Water Melon
Grapes
Orange
kiwi
pears
>>> sorted_fruits = sorted(fruits) # Sorting a List
>>> sorted_fruits
['Apple', 'Banana', 'Grapes', 'Guava', 'Mango', 'Orange', 'Water Melon','kiwi', 'pears']

List Concatenation

>>>some_fruits=[‘Strawberry’,’pomegranate’]
>>>total_fruits=some_fruits+fruits
>>>print(total_fruits)
[‘Banana’, ‘Apple’, ‘Mango’, ‘Guava’, ‘Water Melon’, ‘Grapes’, ‘Orange’, ‘kiwi’, ‘pears’, ‘Strawberry’, ‘pomegranate’]

Convert a string to a List

>>> x=’My name is snigdha’
>>> print(x.split()) #split command will split every word in a sentence and converts to a list
[‘My’, ‘name’, ‘is’, ‘snigdha’]

Convert a list to a string


x=[‘My’, ‘name’, ‘is’, ‘snigdha’]
>>> print(‘ ’.join(x))
My name is snigdha

POP() function:
The pop() function removes (last) element from a list.

>>> fruits
[‘Banana’, ‘Apple’, ‘Mango’, ‘Guava’, ‘Water Melon’, ‘Grapes’, ‘Orange’, ‘kiwi’, ‘pears’]
>>> fruits.pop()
‘pears’
>>> fruits
[‘Banana’, ‘Apple’, ‘Mango’, ‘Guava’, ‘Water Melon’, ‘Grapes’, ‘Orange’, ‘kiwi’]

List Functions

Split(), Index(), Find() with example scenarios

Scenario:
Given a following string:

Game = ‘Xbox 360 | 1000 | New’

Extract and display the string field before the first pipe symbol as “Product”. The field between the two pipe symbols is “Price” of the product, and the last field is the “Condition” of the product.

As a Python programmer/developer your job is to extract the portions of the string field as follows:

Product
Xbox 360

Price
1000

Condition
New

1. Example Using Split():

game=’Xbox 360 | 1000 | New’
>>> game_elements = game.split(‘|’)
>>> game_elements
[‘Xbox 360’, ‘1000’, ‘New’]
>>> Product = game_elements[0]
>>> Product
'Xbox 360 '
>>> Price = game_elements[1]
>>> Price
' 1000 '
>>> Condition = game_elements[2]
>>> Condition
' New'

2. Example using Index():

>>> Game = ‘Xbox 360 | 1000 | New’>>> Game_index = Game.index(‘Xbox 360’) 
# let’s find out the index position of first and last elements:
>>> Game_index
0
>>> Game_last = Game.index(‘New’)
>>> Game_last
18
# let’s extract the Product field from the string field using indexing concept:>>> Game = ‘Xbox 360 | 1000 | New’
>>> Product = Game[ :Game.index(‘|’)] # the indexing starts from 0th position
>>> Product
‘Xbox 360 ‘
# Let’s now find out the index position of the first pipe (|) symbol:>>> Game.index(‘|’)
9
# now let’s extract the Price field:>>> Price = Game[11:15]
>>> Price
‘1000’
# extract the Condition field:>>> Condition = Game[18: ] #index starts from 18th character to end of string
>>> Condition
‘New’

Note: the disadvantage of index() is that it doesn’t give you the index position of second instance of a string or a delimiter.

3.Example using Find():

Find() function will display the index position of any element, delimiter or a string.

Solving the example using find()

>>> Game = ‘Xbox 360 | 1000 | New’# first let’s find the index position of first pipe (|) symbol:>>> Game.find(‘|’)
9
Note: In order to know the position of second pipe symbol, you need to issue a number which is one more than the position of first pipe symbol:>>> Game.find(‘|’, 11)
16
As we know the positions of the two pipe symbols we can easily extract our desired fields.>>> Product = Game[0:9]
>>> Product
‘Xbox 360 ‘
>>> Price = Game[Game.find(‘|’)+1 : Game.find(‘|’,11)]
>>> Price
‘ 1000 ‘
>>> Condition = Game[Game.find(‘|’,11)+1: ]
>>> Condition
‘ New’

List Comprehensions

List comprehension is an elegant way to define and create list in Python. These lists have often the qualities of sets, but are not in all cases of sets.

>>> squares_list = []
>>> for x in range(1,10):
— — — — squares_list.append(x**2)
>>> print(squares_list)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares_listcomp = [x**2 for x in range(1,10)]
>>> print(squares_listcomp)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade