DEV Community

loading...

Introduction To Python Lists

Cindy Achieng
I love to solve problems around me through codes and an Influencer (I know,I see myself that way).I believe programming is powerful and you can do whatever
Originally published at achiengcindy.com on ・6 min read

List is the most versatile python data structure and stores an ordered sequence of elements just like your shopping list or to-do-list.In Python, Lists are mutable,meaning that the elements can be altered unlike tuples or even strings.These elements of a list are called items and can be any data type.

Creating Lists in Python

Creating lists in python is quite simple, use square brackets [] and separate items in the list with commas.
A list can be empty or contain any number of items with different data types (integers,float,strings etc.).

mylist = [ ]  #empty list
mylist2 = [1,2]  # list containing 2 items with integers
mylist3 = [1, 2, 'hello']  # list with 3 items,mixed data types,integers and a string

Note : a list can also hold another list as an item,these are called nested lists. as show below.

mylist4 = [['python','php'],[1,2,3]  # a nested list

Accessing items in a list

We can access items in a list by

  1. Indexing.
    We use the index operator [ ].Each item in a list has an assigned index value. It is important to Note that the index starts from 0 in python and must be an integer

    java python perl ruby c#
    0 1 2 3 4

    Note :The first item of any non-empty list is [0].

    Languages = ['java', 'python', 'perl' 'ruby', 'c#' ]   # define a list
    print(Languages[0]) # Access the first item of a list at index 0
    # Output:java which is the first item on the list.
    
  2. Negative Indexing Python also supports negative indexing.The negative indexing is useful when you want to get the last item in a list because it start accessing a list from the end.

    java python perl ruby c#
    -5 -4 -3 -2 -1

    Note:The last item of any non-empty list is [-1].

    # define a list 
    Languages = ['java', 'python', 'perl' 'ruby', 'c#' ] 
     print(Languages[-1) #Access the last item of a list
    # Output:  C#
    

length of list

Python has useful in-built functions that work with list.We will discuss them later but for now, len() function help us in returning the total number of elements in a list.

# define a list
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
# print the length of the list
print(len(languages)) 
# output 5

Slicing of a List

Slices are good for getting a subset of items in a list.It uses the slicing operator : (colon) to extract part of the sequence.

Languages = ['java', 'python', 'perl','ruby', 'c#' ] # define a list 
# [:3] slicing everything up to but not including index 3
print(languages[:3])  
#Outputs: ['java', 'python', 'perl' ]

# define a list 
Languages = ['java', 'python', 'perl','ruby', 'c#' ]
# [3:] slicing everything from index 3 to the last item
print(languages[3:])
#Output: ['ruby', 'c#' ]


Languages = ['java', 'python', 'perl','ruby', 'c#' ]
#elements from beginning to end
print(languages[:])
#Output: ['java', 'python', 'perl','ruby', 'c#' ]

# define a list 
Languages = ['java', 'python', 'perl','ruby', 'c#' ]
# elements from 1st to 3rd
print(languages[0:3])
Output # ['java', 'python', 'perl']

How to change/add elements in a list

list.append(item)

The method list.append(item) will add the item at the end of a list.

   # define a list
   languages = ['java', 'python' ,'perl', 'ruby', 'c#']
   # append c
   languages.append('c') 
   print (languages)
  # Output : ['java', 'python', 'perl', 'ruby', 'c#', 'c']

list.insert(i, item)

This method will insert an item at the ith position in a list , shifting elements to the right.

# define a list
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
# insert c
languages.insert( 0, 'php') 
print languages 
# Output :  ['php', 'java', 'python', 'perl', 'ruby', 'c#']

list.extend(items)

The extend method concatenates lists. Note that you do not call extend with multiple arguments;it takes in a second list as its argument.

# define a list
languages = ['java', 'python' ,'perl', 'ruby', 'c#']

Languages2=['c++', 'c'] # define a second list

languages.extend(Languages2)

print(languages)

# Output ['java', 'python', 'perl', 'ruby', 'c#', 'c++', 'c']

extend method does not return any value,instead it modifies the original list by adding the content of the second list

Deleting List Elements

Use the del keywords to delete an item at specific index

  • single item

     languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # define a list
     del languages[2] # use del keyword
     print(languages)
     # Output removes perl ['java', 'python', 'ruby', 'c#']
    
  • Multiple items

     languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # define a list
     del languages[1:3]  #delete Multiple items by slicing
     print(languages)
    
     # Output : ['java', 'ruby', 'c#'] 
    

list.remove(item)

It will search and remove only the first occurrence of an item

Languages = ['java', 'python', 'perl','python','ruby', 'c#' ]
Languages.remove('python')  # the first occurrence of python
print(languages) # outputs ['java', 'perl', 'python', 'ruby', 'c#']

It removes the python after java'.Note that the 'python' after perl is still present

list.pop()

Removes and returns the last item of a list

languages = ['java', 'python' ,'perl', 'ruby', 'c#']

print(languages.pop()) # print c#

print(languages)
# output ['java', 'python', 'perl', 'ruby']

list.pop(i)

Removes and returns the ith item of a list

Languages = ['java', 'python', 'perl','ruby', 'c#' ]
print(languages.pop(1)) # removes  index 1 item
#  Output returns Python

list.index(item)

When lists start to get long, it becomes more difficult for us to count out our items to determine at what index position a certain value is located. We can use list.index(item), to return the index in the list where that item is located.
If there is more than one item with value item, this method will return the first occurrence.

Summary of list methods

Method Name Description
1 alist.append(item) Adds a new item at the end of the list
2 alist.insert(i, item) Insert item at the ith position shifting other items to the right.
3 alist.extend() Adds the elements of a second list to the original list
4 del alist[i] Deletes the item at the ith position,it can also a range of items by the use of slicing
5 alist.remove(item) Search and remove the first occurrence of an item,does not return a new list and throws an error if not found
6 pop() Removes and returns the last item of a list
7 pop(i) Removes and returns the i item of a list
8 alist.index(item) Returns the index of first occurrence
9 alist.sort() sort the items of a list
10 alist.reverse() Reverses a List
11 alist.count(item) Returns the count of occurrence of an item

Common List Operations

Concatenation

Concatenation uses the + Operator. It Combines lists.

# define a list
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
print(languages +(['c++', 'c']))
# Output:  ['java', 'python' ,'perl', 'ruby', 'c#', c++, c]

Repetition

uses the * Operator. Concatenates a list a repeated number of times

 mylist = ['strings are  cool'] * 2
 print (mylist)
# output:  ['strings are  cool', 'strings are  cool']

Membership

Keyword In is used to test if an item is a member of a list.

languages = ['java', 'python' ,'perl', 'ruby', 'c#']
if 'python' in languages:
    print('right')

Iteration

For Loop is used to iterate through each element on a list with the keyword in.The for loop allows you to to perform an action for every element in the list.

illustration 1

languages = ['java', 'python' ,'perl', 'ruby', 'c#']
for i in languages:
   print(i)

This will print the all the items in the list one per line as shown below:

java
python
perl
ruby
c#

illustration 2

random_sum = [2,7,8,9]
total = 0
for i in random_sum:
    total +=i
print total

The above code will print 26,the sum of all the items of the list.
The for loop requires a variable to hold the items being iterated and the source.

While Loop will first check the condition .If the condition is true,it will keep iterating and terminates the loop once the condition turns false.

languages = ['java', 'python' ,'perl', 'ruby', 'c#']
i = 0
while i <len(languages):
    print(languages[i])
    i = i+3

The above codes will print

java
ruby




Conclusion

Now you know what lists are and how to manipulate them.For further understanding on list, read about list comprehension.

Discussion (8)

Collapse
xoeseko profile image
Xoeseko

Nice intro! I think you had a couple typos though

list.extend 
#output: c++ and c are missing

Then,

list.pop()

You have an index in the first one too.

I was also surprised you didn't give the output for the last methods you showed.

Nice writing otherwise keep it up

Collapse
cindyachieng profile image
Cindy Achieng Author

I understand the misunderstanding on extend() method and I have used a more clear example by defining a second list

languages = ['java', 'python' ,'perl', 'ruby', 'c#']

Languages2=['c++', 'c']

languages.extend(Languages2)

print(languages)
# Output ['java', 'python', 'perl', 'ruby', 'c#', 'c++', 'c']

You are right, when we simply use Pop() without specifying the item position,It removes the last item and returns the value which has been removed

languages = ['java', 'python' ,'perl', 'ruby', 'c#']

print(languages.pop()) # returns c#, the last index

print(languages) # print the  after removing c#

# output ['java', 'python', 'perl', 'ruby']

Thanks

Collapse
cindyachieng profile image
Cindy Achieng Author

Thank you for that observation,I will edit the post soon enough

Collapse
buntine profile image
Andrew Buntine

Nice one. An article on list comprehensions or Pythons built-in list processing functions would be a cool follow-up.

Collapse
cindyachieng profile image
Cindy Achieng Author

Sure,I will try and put it up by the end of the week.

Collapse
tonaain profile image
Toni

Thank you for this article Cindy! It helped to answer a few questions I had.👍

Collapse
georgeoffley profile image
George Offley

Great job!

Collapse
cindyachieng profile image
Cindy Achieng Author

Thanks George