Lists in python



  • Creating Lists in python
  • Insert,Delete and Append Operations in Lists
  • Sorting ascending and descending in Lists in python
  • Using for,if and while loops with lists in python


Python has a great built-in list type named “list”. List literals are written within square brackets [ ]. Lists work similarly to strings, use the len() function and square brackets [ ] to access data, with the first element at index 0.

Creating List

Lets create a list of colors and print them using their index.

# Python Lists
# @IdiotInside_

print ("Creating List:")
colors = ['red', 'blue', 'green']
print (colors[0])   ## red
print (colors[2])    ## green
print (len(colors))  ## 3

List Manipulation

Now append,insert and remove elements from the list and perform ascending order and descending order sorting in python.

# Python Lists
# @IdiotInside_

print ("Creating List:")
colors = ['red', 'blue', 'green']
print (colors[0])   ## red
print (colors[1])   ## blue
print (colors[2])    ## green
print (len(colors))  ## 3

print ("Append to the List")
print (colors[3]) ##orange

print ("Insert to the List")
colors.insert(3, "yellow")
print (colors[3]) ##yellow
print (colors[4]) ##orange

print ("Remove from the List")
print (colors[1])   ## blue
colors.remove("blue") ## deletes blue and shifts elements to the left
print (colors[1])   ## green  

print ("Sorting Ascending order using sorted")
nums = [98,22,45,30]
numsAsc = sorted(nums)
print (numsAsc[0])   ## 22
print (numsAsc[1])   ## 30
print (numsAsc[2])    ## 45

print ("Sorting Descending order using sorted")
numsDesc = sorted(nums,reverse=True)
print (numsDesc[0])   ## 98
print (numsDesc[1])   ## 45
print (numsDesc[2])    ## 30

Using for loops with lists

Python’s for and in constructs are extremely useful, and the first use of them we’ll see is with lists. The for construct

for var in list is an easy way to look at each element in a list (or other collection). Do not add or remove from the list during iteration.

# Python Lists
# @IdiotInside_

nos = [1, 4, 9, 16, 25]
sum = 0
for num in nos:
    sum += num
print (sum)  ## 55

Using if loop with lists

The in construct on its own is an easy way to test if an element appears in a list. if the value is in the collection, returning True/False.

# Python Lists
# @IdiotInside_

colors = ['red', 'blue', 'green']
if 'blue' in colors:
    print ('cool')  # blue found in the list

Using while loops with lists

Python also has the standard while-loop, and the break and continue statements work as in C++ and Java, altering the course of the innermost loop. The above for/in loops solves the common case of iterating over every element in a list, but the while loop gives you total control over the index numbers. Here’s a while loop which accesses every 3rd element in a list:

# Python Lists
# @IdiotInside_

# Access every 3rd element in a list
i = 0
a = [1,2,3,4,5,6,7,8,9]
while i < len(a):
    print (a[i])  #prints 1 4 7
    i = i + 3

List Methods

Here are some other common list methods.
list.append(elem) adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
list.insert(index, elem) inserts the element at the given index, shifting elements to the right.
list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
list.index(elem) searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use “in” to check without a ValueError).
list.remove(elem) searches for the first instance of the given element and removes it (throws ValueError if not present)
list.sort() sorts the list in place (does not return it). (The sorted() function shown below is preferred.)
sorted(list) returns a new sorted list from the items in iterable.
list.reverse() reverses the list in place (does not return it)
list.pop(index) removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).