Working with lists and tuples in Python

Share

Since most of the early programmers grab the concept of the handling data such as number and string, conditional statements, iteration, use of break and continue statement more easily, this article will explain the use and implementation of the collection of data items in Python.

For example, you might need to store the collection of the strings or numbers, this article will help you understand the use of tuples and lists.

Skills Required

A list lets you store a list of items. Since a list stores  these items in the sequence, in which they are added to the list, lists are type of data structure known as a sequence. In some programming language it is referred to as array, and the items in the array is known as the elements.

Syntax for creating a list

Code that creates lists:

Most of the time a list contains the data items of similar data type. However, you might sometimes need to create a list of different data types as shown in the example 3. Finally, you might sometimes need to crate an empty list.

Positive and Negative index in a list:

How to get an item in a list:

Code that gets items from the inventory list:

How to set an item in the list:

Description

  • A list contains collection of items.
  • To refer to the items in the list, you use an index where 0 refers to the first item, 1 refers to the second item and so on.
  • You can also use negative values as index where -1 refers to the last item in the list, -2 refers to the second last item and so on.
  • You can use the repetition operator(*) to repeat the items in the list. This can be good way to set the initial values to some default values.

How to add and remove items:

There are methods that are available for performing operations on the lists:

  • append(item)
  • insert(index, item)
  • remove(item)
  • index(item)
  • pop([index])

How to use the append(), insert() and remove() methods

stats

About Dhiraj 46 Articles
Blogger on development, securities, and efficiency on web technologies.

Be the first to comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.