Introduction To Python Lists

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
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
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

Enter fullscreen mode Exit fullscreen mode

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
mylist4 = [['python','php'],[1,2,3]  # a nested list
mylist4 = [['python','php'],[1,2,3] # a nested list

Enter fullscreen mode Exit fullscreen mode

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.
    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.
    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#
    # define a list 
    Languages = ['java', 'python', 'perl' 'ruby', 'c#' ] 
     print(Languages[-1) #Access the last item of a list
    # Output:  C#
    # 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
# define a list
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
# print the length of the list
print(len(languages)) 
# output 5
# define a list languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # print the length of the list print(len(languages)) # output 5

Enter fullscreen mode Exit fullscreen mode

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']
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']
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']

Enter fullscreen mode Exit fullscreen mode

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']
   # define a list
   languages = ['java', 'python' ,'perl', 'ruby', 'c#']
   # append c
   languages.append('c') 
   print (languages)
  # Output : ['java', 'python', 'perl', 'ruby', 'c#', 'c']
# define a list languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # append c languages.append('c') print (languages) # Output : ['java', 'python', 'perl', 'ruby', 'c#', 'c']

Enter fullscreen mode Exit fullscreen mode

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#']
# define a list
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
# insert c
languages.insert( 0, 'php') 
print languages 
# Output :  ['php', 'java', 'python', 'perl', 'ruby', 'c#']
# define a list languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # insert c languages.insert( 0, 'php') print languages # Output : ['php', 'java', 'python', 'perl', 'ruby', 'c#']

Enter fullscreen mode Exit fullscreen mode

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']
# 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']
# 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']

Enter fullscreen mode Exit fullscreen mode

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#']
     languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # define a list
     del languages[2] # use del keyword
     print(languages)
     # Output removes perl ['java', 'python', 'ruby', 'c#']
    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#']
     languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # define a list
     del languages[1:3]  #delete Multiple items by slicing
     print(languages)
    
     # Output : ['java', 'ruby', 'c#'] 
    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#']
Languages = ['java', 'python', 'perl','python','ruby', 'c#' ]
Languages.remove('python')  # the first occurrence of python
print(languages) # outputs ['java', 'perl', 'python', 'ruby', 'c#']
Languages = ['java', 'python', 'perl','python','ruby', 'c#' ] Languages.remove('python') # the first occurrence of python print(languages) # outputs ['java', 'perl', 'python', 'ruby', 'c#']

Enter fullscreen mode Exit fullscreen mode

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']
languages = ['java', 'python' ,'perl', 'ruby', 'c#']

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

print(languages)
# output ['java', 'python', 'perl', 'ruby']
languages = ['java', 'python' ,'perl', 'ruby', 'c#'] print(languages.pop()) # print c# print(languages) # output ['java', 'python', 'perl', 'ruby']

Enter fullscreen mode Exit fullscreen mode

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
Languages = ['java', 'python', 'perl','ruby', 'c#' ]
print(languages.pop(1)) # removes  index 1 item
#  Output returns Python
Languages = ['java', 'python', 'perl','ruby', 'c#' ] print(languages.pop(1)) # removes index 1 item # Output returns Python

Enter fullscreen mode Exit fullscreen mode

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]
# define a list
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
print(languages +(['c++', 'c']))
# Output:  ['java', 'python' ,'perl', 'ruby', 'c#', c++, c]
# define a list languages = ['java', 'python' ,'perl', 'ruby', 'c#'] print(languages +(['c++', 'c'])) # Output: ['java', 'python' ,'perl', 'ruby', 'c#', c++, c]

Enter fullscreen mode Exit fullscreen mode

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']
 mylist = ['strings are  cool'] * 2
 print (mylist)
# output:  ['strings are  cool', 'strings are  cool']
mylist = ['strings are cool'] * 2 print (mylist) # output: ['strings are cool', 'strings are cool']

Enter fullscreen mode Exit fullscreen mode

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')
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
if 'python' in languages:
    print('right')
languages = ['java', 'python' ,'perl', 'ruby', 'c#'] if 'python' in languages: print('right')

Enter fullscreen mode Exit fullscreen mode

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)
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
for i in languages:
   print(i)
languages = ['java', 'python' ,'perl', 'ruby', 'c#'] for i in languages: print(i)

Enter fullscreen mode Exit fullscreen mode

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

java
python
perl
ruby
c#
java
python
perl
ruby
c#
java python perl ruby c#

Enter fullscreen mode Exit fullscreen mode

illustration 2

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

Enter fullscreen mode Exit fullscreen mode

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
languages = ['java', 'python' ,'perl', 'ruby', 'c#']
i = 0
while i <len(languages):
    print(languages[i])
    i = i+3
languages = ['java', 'python' ,'perl', 'ruby', 'c#'] i = 0 while i <len(languages): print(languages[i]) i = i+3

Enter fullscreen mode Exit fullscreen mode

The above codes will print

java<br>
ruby<br>
java<br>
ruby<br>
java
ruby

Enter fullscreen mode Exit fullscreen mode



Conclusion

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

原文链接:Introduction To Python Lists

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
The shortest way to do many things is to only one thing at a time.
做许多事情的捷径就是一次只做一件一件事
评论 抢沙发

请登录后发表评论

    暂无评论内容